Python如何操作JSON数据
在Python中处理JSON数据通常涉及以下步骤:
1,导入json模块。
2,使用json.loads()将JSON格式的字符串解析为Python中的数据类型(通常是字典或列表)。
3,使用json.dumps()将Python字典或列表转换回JSON格式的字符串。
4,使用json.load()从文件中加载JSON数据。
5,使用json.dump()将数据写入文件,以JSON格式保存。
示例代码:
import json
# 解析JSON字符串到Python数据类型,这里给定字符串,也可以是接口返回
data_str = '{"name": "John", "age": 30, "city": "New York"}'
parsed_data = json.loads(data_str)
print(parsed_data) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
# 将Python数据类型字典转换为JSON字符串
python_dict = {"name": "Jane", "age": 25, "city": "Los Angeles"}
json_str = json.dumps(python_dict)
print(json_str) # 输出: {"name": "Jane", "age": 25, "city": "Los Angeles"}
# 从物理文件中加载JSON数据,假设当前文件夹有文件名为data.json,
with open('data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)
# 将python数据类型python_dict写入文件名为data.json的文件,以JSON格式保存,
with open('data.json', 'w') as file:
json.dump(python_dict, file)
欢迎拍砖讨论...
原文地址:https://blog.csdn.net/shenzhenNBA/article/details/142321383
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!