1、json.loads()
使用json.loads()
将JSON格式的字符串解析为Python中的数据类型(通常是字典或列表)。
import json
# 解析JSON字符串为Python数据类型
json_string = '{"name": "John", "age": 30, "city": "New York"}'
parsed_data = json.loads(json_string)
print(parsed_data) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
2、json.dumps()
使用json.dumps()
将Python字典或列表转换回JSON格式的字符串。
import json
# 将Python字典转换为JSON字符串
python_dict = {"name": "Jane", "age": 25, "city": "Los Angeles"}
json_string = json.dumps(python_dict)
print(json_string) # 输出: {"name": "Jane", "age": 25, "city": "Los Angeles"}
3、json.load()
使用json.load()
从文件中加载JSON数据。
import json
# 从文件加载JSON数据
with open('data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)
4、json.dump()
使用json.dump()
将数据写入文件,保存为JSON格式。
import json
# 将数据写入文件
data_to_dump = {"name": "Bob", "age": 22, "city": "Chicago"}
with open('data.json', 'w') as file:
json.dump(data_to_dump, file)