上一篇
Python读取JSON文件教程 - 完整指南与示例 | Python数据处理
- Python
- 2025-07-31
- 1650
Python读取JSON文件完全指南
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,在Python中处理JSON文件非常简单。本教程将教你如何使用Python内置的json
模块读取JSON文件。
为什么使用JSON?
- 轻量级且易于阅读的数据格式
- 与多种编程语言兼容
- 常用于API数据交换和配置文件
- Python原生支持,无需额外安装
基本步骤:读取JSON文件
Python读取JSON文件只需三个简单步骤:
- 导入内置的
json
模块 - 使用
open()
函数打开JSON文件 - 使用
json.load()
方法解析文件内容
示例代码:读取简单JSON文件
import json # 1. 打开JSON文件 with open('data.json', 'r', encoding='utf-8') as file: # 2. 加载JSON数据 data = json.load(file) # 3. 使用数据 print(data) print("姓名:", data["name"]) print("年龄:", data["age"])
data.json文件内容
{ "name": "张三", "age": 28, "city": "北京", "is_student": false, "courses": ["Python", "数据分析", "机器学习"] }
输出结果
{ 'name': '张三', 'age': 28, 'city': '北京', 'is_student': False, 'courses': ['Python', '数据分析', '机器学习'] } 姓名: 张三 年龄: 28
处理复杂JSON结构
当JSON数据包含嵌套结构时,我们可以使用递归或逐层访问的方式提取数据。
示例:读取嵌套JSON数据
import json with open('employees.json', 'r', encoding='utf-8') as file: employees = json.load(file) # 访问嵌套数据 print("公司名称:", employees["company"]["name"]) print("员工总数:", len(employees["employees"])) # 遍历员工数据 for employee in employees["employees"]: print(f"\n员工ID: {employee['id']}") print(f"姓名: {employee['name']}") print(f"职位: {employee['position']}") print("技能:", ", ".join(employee["skills"]))
employees.json文件内容
{ "company": { "name": "科技先锋有限公司", "established": 2010 }, "employees": [ { "id": 101, "name": "李四", "position": "高级开发工程师", "salary": 25000, "skills": ["Python", "Django", "数据库"] }, { "id": 102, "name": "王芳", "position": "数据分析师", "salary": 22000, "skills": ["Python", "Pandas", "数据可视化"] }, { "id": 103, "name": "赵明", "position": "前端工程师", "salary": 20000, "skills": ["JavaScript", "React", "CSS"] } ] }
处理大型JSON文件
对于大型JSON文件,可以使用json.loads()
逐行读取:
逐行读取大型JSON文件
import json # 适用于每行是一个独立JSON对象的大型文件 data_list = [] with open('large_data.json', 'r', encoding='utf-8') as file: for line in file: # 解析每一行的JSON对象 obj = json.loads(line) data_list.append(obj) print(f"成功读取 {len(data_list)} 个JSON对象")
常见问题与解决方案
1. JSONDecodeError: 文件格式错误
使用JSON验证工具检查文件格式,确保没有逗号错误或引号不匹配问题。
2. UnicodeDecodeError: 编码问题
在open()
函数中指定正确的编码格式,通常使用encoding='utf-8'
。
3. 处理日期等特殊格式
JSON不支持日期类型,需要将日期字符串转换为datetime对象:
from datetime import datetime # 转换日期字符串 date_str = data["create_date"] create_date = datetime.strptime(date_str, "%Y-%m-%d")
最佳实践总结
- 始终使用
with open()
语句确保文件正确关闭 - 指定文件编码(特别是中文内容)
- 处理大型文件时考虑逐行读取
- 使用
json.dumps(data, indent=4)
可以美化输出JSON - 验证外部JSON数据来源的可靠性
现在你已经掌握了Python读取JSON文件的各种技巧!尝试在自己的项目中使用JSON存储和读取数据吧。
本文由MengKu于2025-07-31发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://www.521pj.cn/20256932.html
发表评论