在Python中处理JSON文件可以使用json模块。下面是一些常见的JSON操作示例:
import json# 打开JSON文件with open('data.json', 'r') as f: # 解析JSON数据 data = json.load(f)# 使用data变量访问JSON中的数据print(data)写入JSON文件import json# 要写入的数据data = { 'name': 'John', 'age': 30, 'city': 'New York'}# 打开JSON文件with open('data.json', 'w') as f: # 将数据写入JSON文件 json.dump(data, f)将JSON字符串转换为Python对象import json# JSON字符串json_str = '{"name": "John", "age": 30, "city": "New York"}'# 将JSON字符串转换为Python对象data = json.loads(json_str)# 使用data变量访问Python对象中的数据print(data['name'])将Python对象转换为JSON字符串import json# Python对象data = { 'name': 'John', 'age': 30, 'city': 'New York'}# 将Python对象转换为JSON字符串json_str = json.dumps(data)# 输出JSON字符串print(json_str)以上示例中,json.load()用于从文件中读取JSON数据,json.dump()用于将数据写入JSON文件。json.loads()用于将JSON字符串转换为Python对象,json.dumps()用于将Python对象转换为JSON字符串。

