Python如何读取JSON文件:从基础到实用技巧
JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,因其易读性和与语言无关的特性,在Web开发、API交互、配置文件存储等领域被广泛应用,Python内置了对JSON格式的强大支持,通过json模块可以轻松实现JSON文件的读取与解析,本文将从基础语法到实用技巧,详细介绍Python如何读取JSON文件,帮助开发者快速这一核心技能。
基础入门:使用json.load()读取JSON文件
Python的json模块提供了json.load()函数,专门用于从文件对象中读取JSON数据并转换为Python对象(如字典、列表等),其基本语法如下:
import json
# 打开JSON文件(默认以文本模式'r'打开)
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file) # 将JSON数据解析为Python对象
关键步骤解析:
- 导入模块:首先需要导入Python内置的
json模块。 - 打开文件:使用
open()函数以只读文本模式('r')打开JSON文件,推荐显式指定encoding='utf-8',避免因编码问题导致解析错误。 - 读取并解析:通过
json.load(file)将文件对象中的JSON字符串转换为对应的Python对象:- JSON对象()→ Python字典(
dict) - JSON数组(
[])→ Python列表(list) - JSON字符串()→ Python字符串(
str) - JSON数字(
123/3)→ Python整数(int)/浮点数(float) - JSON布尔值(
true/false)→ Python布尔值(True/False) - JSON空值(
null)→ PythonNone
- JSON对象()→ Python字典(
示例演示
假设有一个名为data.json的文件,内容如下:
{
"name": "张三",
"age": 25,
"is_student": false,
"courses": ["Python", "JavaScript"],
"address": {
"city": "北京",
"district": "海淀区"
},
"scores": null
}
通过以下代码读取并解析该文件:
import json
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(data)
print(type(data)) # 输出:<class 'dict'>
print(data["name"]) # 输出:张三
print(data["courses"][0]) # 输出:Python
print(data["address"]["city"]) # 输出:北京
输出结果为:
{'name': '张三', 'age': 25, 'is_student': False, 'courses': ['Python', 'JavaScript'], 'address': {'city': '北京', 'district': '海淀区'}, 'scores': None}
<class 'dict'>
张三
Python
北京
进阶技巧:处理复杂场景与异常
读取JSON字符串而非文件:json.loads()
如果JSON数据已经以字符串形式存在(例如从API响应或用户输入获取),可以使用json.loads()(注意有个s,代表“string”)进行解析:
json_str = '{"name": "李四", "age": 30}'
data = json.loads(json_str)
print(data["name"]) # 输出:李四
处理文件路径异常:try-except与os.path
在实际开发中,JSON文件可能不存在或路径错误,需通过异常处理增强代码健壮性:
import json
import os
file_path = 'nonexistent.json'
try:
if not os.path.exists(file_path):
raise FileNotFoundError(f"文件 {file_path} 不存在")
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except FileNotFoundError as e:
print(f"错误:{e}")
except json.JSONDecodeError as e:
print(f"JSON解析错误:{e}")
except Exception as e:
print(f"未知错误:{e}")
处理大文件:逐行读取与json.JSONDecoder
对于超大型JSON文件(如GB级别),直接使用json.load()可能导致内存不足,此时可采用逐行读取的方式,结合json.JSONDecoder流式解析:
import json
def read_large_json(file_path):
decoder = json.JSONDecoder()
buffer = ""
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
buffer += line.strip()
try:
# 尝试解析buffer中的完整JSON对象
while buffer:
data, idx = decoder.raw_decode(buffer)
yield data # 生成一个JSON对象
buffer = buffer[idx:].lstrip() # 移除已解析的部分
except json.JSONDecodeError:
continue # 当前buffer不完整,继续读取下一行
# 示例:假设large_file.json每行是一个独立的JSON对象(如JSON Lines格式)
for obj in read_large_json('large_file.json'):
print(obj) # 逐个处理JSON对象
处理编码问题:encoding参数
如果JSON文件使用非UTF-8编码(如GBK),需在open()中指定正确的编码:
with open('data_gbk.json', 'r', encoding='gbk') as f:
data = json.load(f)
自定义解析行为:object_hook与parse_float等
json.load()支持通过参数控制解析行为,
object_hook:将解析出的字典转换为自定义对象(例如ORM模型)。parse_float:自定义浮点数解析方式(例如转换为decimal.Decimal)。
示例:使用object_hook转换为自定义类
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
def person_decoder(dct):
if "name" in dct and "age" in dct:
return Person(dct["name"], dct["age"])
return dct
json_str = '{"name": "王五", "age": 28}'
data = json.loads(json_str, object_hook=person_decoder)
print(data) # 输出:Person(name=王五, age=28)
print(type(data)) # 输出:<class '__main__.Person'>
常见问题与解决方案
问题:json.load()报错JSONDecodeError: Invalid control character at position
原因:JSON文件中包含不可见的控制字符(如换行符\n、制表符\t),且未正确转义。
解决:
- 检查文件内容,确保控制字符被转义(例如
\n应写作\\n)。 - 使用
json.tool命令行工具格式化JSON文件,修复语法错误:python -m json.tool data.json > formatted_data.json
问题:读取中文显示为乱码
原因:文件编码与open()的encoding参数不匹配(例如文件是UTF-8,但未指定encoding='utf-8')。
解决:
- 使用文本编辑器(如VS Code、Sublime Text)检查文件编码,确保
open()中指定的编码一致。
问题:JSON文件是数组,如何逐条处理?
示例文件(array.json):
[
{"id": 1, "name": "item1"},
{"id": 2, "name": "item2"},
{"id": 3, "name": "item3"}
]
代码:
import json
with open('array.json', 'r', encoding='utf-8') as f:
data_list = json.load(f) # 解析为列表
for item in data_list:
print(f"ID: {item['id']}, Name: {item['name']}")
输出:
ID: 1, Name: item1
ID: 2, Name: item2
ID: 3, Name: item3
Python读取JSON文件的核心是json.load()函数,其操作流程简单明了:打开文件→读取并解析→转换为Python对象,通过结合异常处理、流式解析、自定义解码器等技巧,可以应对各种复杂场景(大文件、编码问题、自定义数据结构等),这些方法,不仅能高效处理JSON数据,还能为后续的数据分析、API交互等任务奠定坚实基础。
无论是初学者还是资深开发者,都



还没有评论,来说两句吧...