上一篇
数据处理 | 格式转换
Python解析JSON数据
json
模块(无需安装,直接import json
)。 json.loads()
:解析字符串格式的JSON → Python对象。 json.load()
:从文件读取JSON → Python对象。 json.dumps()
:Python对象 → JSON格式字符串。 json.dump()
:Python对象 → 写入JSON文件。 实例详解
import json # 🌰 示例1:解析JSON字符串 json_str = '{"name": "Alice", "age": 25, "skills": ["Python", "SQL"]}' data = json.loads(json_str) print(data["skills"]) # 输出: ['Python', 'SQL'] # 🌰 示例2:写入JSON文件 user_data = {"id": 101, "is_active": True} with open("user.json", "w") as f: json.dump(user_data, f, indent=4) # indent美化格式
注意事项
try-except
捕获json.JSONDecodeError
(无效JSON时抛出)。 null
→ Python None
true/false
→ Python True/False
进阶技巧
json.JSONEncoder
处理复杂对象(如日期)。 ijson
库(流式解析)。 💡 2025-07参考:Python官方文档、主流技术社区实践案例。
本文由 永向松 于2025-07-31发表在【云服务器提供商】,文中图片由(永向松)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/498067.html
发表评论