🐍
Python JSON处理
Python内置json模块,使用简单方便
解析JSON
import json
# 解析JSON字符串
json_str = '{"name": "张三", "age": 25}'
data = json.loads(json_str)
print(data['name']) # 输出: 张三
# 读取JSON文件
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(data)生成JSON
import json
# 将Python对象转为JSON字符串
data = {"name": "张三", "age": 25}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# 写入JSON文件
with open('output.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)实用技巧
- 使用 ensure_ascii=False 保留中文字符
- 使用 indent 参数美化输出
- 使用 object_hook 自定义反序列化