PYTHON JSON处理
Python 提供了内置的 json 模块,用于处理 JSON (JavaScript Object Notation) 数据。JSON 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。以下是一些基本的 JSON 处理操作:
导入 json 模块:
import json
将 Python 对象转换成 JSON 字符串:
使用 json.dumps() 方法将 Python 字典或列表转换成 JSON 格式的字符串。
data = {"name": "John", "age": 30, "city": "New York"} json_string = json.dumps(data) print(json_string)
将 JSON 字符串转换成 Python 对象:
使用 json.loads() 方法将 JSON 格式的字符串解析成 Python 字典。
json_string = '{"name": "John", "age": 30, "city": "New York"}' data = json.loads(json_string) print(data)
读取和写入 JSON 文件:
写入 JSON 数据到文件:
with open('data.json', 'w') as f: json.dump(data, f)
从文件读取 JSON 数据:
with open('data.json', 'r') as f: data = json.load(f)
美化 JSON 输出:
json.dumps() 方法可以接受 indent 参数来美化输出的 JSON 字符串。
pretty_json_string = json.dumps(data, indent=4) print(pretty_json_string)
处理 JSON 编码问题:
如果 JSON 数据包含非 ASCII 字符,可以使用 ensure_ascii=False 参数来避免这些字符被转义。
json_string = json.dumps(data, ensure_ascii=False)
使用 JSONPath 表达式:
jsonpath-ng 是一个 Python 库,可以用来查询 JSON 数据,类似于 XPath 用于 XML。
from jsonpath_ng import jsonpath, parse jsonpath_expr = parse('$.store.book[*].author') result = [match.value for match in jsonpath_expr.find(data)] print(result)
这些是处理 JSON 数据的一些基本方法。如果你有更具体的问题或需要示例代码,请随时提问。