在Python中使用JSON模块,主要涉及以下步骤和函数:
导入JSON模块
import json
将Python对象转换为JSON字符串
person = {"name": "John", "age": 30}
person_string = json.dumps(person)
将JSON字符串转换为Python对象
person_object = json.loads(person_string)
访问Python对象中的属性
print(person_object["name"]) 输出 John
从文件中读取JSON数据
with open('kel.txt', 'r', encoding='utf-8') as file:
data = json.load(file)
将Python对象编码为JSON字符串
data = [{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]
data_string = json.dumps(data)
将JSON字符串解码为Python对象
data_object = json.loads(data_string, encoding='utf-8')
在命令行上漂亮打印并验证JSON
import json
import pprint
with open('kel.txt', 'r', encoding='utf-8') as file:
data = json.load(file)
pprint.pprint(data)
使用JMESPath对JSON文档进行高级查询
import json
import jq
data = [{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]
使用jq查询
result = jq.compile('.a + .b + .c').input(data).all()
print(result)
以上是Python中使用JSON模块的基本方法。您可以根据需要选择不同的函数进行操作。