Python中JSON使用指南:从基础到高效技巧
Python中JSON使用指南:从基础到高效技巧
JSON(JavaScript Object Notation)是轻量级的数据交换格式,凭借易读性和跨平台特性,成为现代开发中不可或缺的工具。Python内置的
json
库提供了完整的JSON处理功能,以下是核心用法及实用技巧。
一、JSON与Python的对应关系
JSON与Python数据类型可相互转换:
- JSON → Python:
object
→字典、array
→列表、string
→字符串、number
→整数/浮点数、true
/false
→True
/False
、null
→None
- Python → JSON:字典→
object
、列表/元组→array
、None
→null
等
二、核心方法
1. 字符串与对象的转换
- 解码JSON字符串:
json.loads()
import json json_str = '{"name": "John", "age": 30}' data = json.loads(json_str) # 输出字典:{'name': 'John', 'age': 30}
- 编码为JSON字符串:
json.dumps()
data = {"city": "New York", "population": 8.4e6} json_str = json.dumps(data) # 输出字符串:{"city": "New York", "population": 8400000.0}
2. 文件读写
- 从文件读取JSON:
json.load()
with open("data.json", "r") as f: data = json.load(f)
- 写入JSON到文件:
json.dump()
with open("output.json", "w") as f: json.dump(data, f)
三、美化与优化
1. 格式化输出
通过
indent
和sort_keys
参数增强可读性:json_str = json.dumps(data, indent=2, sort_keys=True)
2. 处理中文
设置
ensure_ascii=False
避免Unicode转义:json.dumps({"姓名": "张三"}, ensure_ascii=False) # 输出:{"姓名": "张三"}
四、高级技巧
1. 命令行工具
验证或格式化JSON文件:
python3 -m json.tool input.json
2. JMESPath查询
安装
jmespath
后快速提取嵌套数据:import jmespath data = {"users": [{"name": "Alice"}, {"name": "Bob"}]} result = jmespath.search("users[*].name", data) # 输出:['Alice', 'Bob']
3. 处理复杂结构
递归处理嵌套字典/列表:
def process(data): if isinstance(data, dict): return {k: process(v) for k, v in data.items()} elif isinstance(data, list): return [process(item) for item in data] else: return data
五、总结
Python的
json
库功能强大,覆盖从基础转换到文件操作的完整需求。推荐工具:
- simplejson:支持高精度数值处理的第三方库
- describejson:快速分析大型JSON结构