在Python中,可以使用import json语句导入json模块,然后使用该模块中的函数和类来处理JSON数据。
下面是json模块的一些常用函数和类的示例用法:
import json# JSON字符串json_str = '{"name": "John", "age": 30, "city": "New York"}'# 将JSON字符串转换为Python对象python_obj = json.loads(json_str)print(python_obj) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}将Python对象转换为JSON字符串:import json# Python对象python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}# 将Python对象转换为JSON字符串json_str = json.dumps(python_obj)print(json_str) # 输出: {"name": "John", "age": 30, "city": "New York"}读取JSON文件并解析为Python对象:import json# 读取JSON文件with open('data.json') as json_file: json_str = json_file.read()# 解析JSON字符串为Python对象python_obj = json.loads(json_str)print(python_obj)将Python对象写入JSON文件:import json# Python对象python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}# 将Python对象转换为JSON字符串json_str = json.dumps(python_obj)# 将JSON字符串写入文件with open('data.json', 'w') as json_file: json_file.write(json_str)这些只是json模块的一些基本用法示例,json模块还提供了其他函数和类来处理更复杂的JSON数据,你可以查看官方文档来了解更多信息:json - Python标准库文档

