Python读取JSON文件教程:标准库json详解
用Python标准库json读取本地JSON文件,支持dict和list两种根结构,中文不转义、处理嵌套字段,附完整可运行代码。
场景痛点
接口返回的数据、配置文件、前端传过来的数据都是JSON格式。直接记事本看一堆大括号看不懂,想提取其中某个字段做分析、存进CSV,就得用Python的json模块。标准库自带,不用装任何东西,读进来就是Python字典,随便取。
用到的库
# 纯标准库,无需pip安装
完整代码
# 用Python标准库读取JSON文件
import json
def read_json_dict(file_path):
"""读取根是对象{}的JSON,返回dict。"""
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
print("类型:", type(data))
print("顶层keys:", list(data.keys()) if isinstance(data, dict) else "不是dict")
return data
def read_json_list(file_path):
"""读取根是数组[]的JSON,返回list。"""
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
print(f"共 {len(data)} 条记录")
if data:
print("第一条keys:", list(data[0].keys()))
return data
def extract_fields(data, fields):
"""
从list[dict]里抽取指定字段,方便后续转CSV。
"""
result = []
for item in data:
row = {}
for f in fields:
# 支持点号路径,比如 "user.name"
row[f] = _get_nested(item, f)
result.append(row)
return result
def _get_nested(d, dotted_key):
"""按 a.b.c 这种点号路径取值,取不到返回None。"""
keys = dotted_key.split(".")
cur = d
for k in keys:
if isinstance(cur, dict) and k in cur:
cur = cur[k]
else:
return None
return cur
def main():
# 根是对象的JSON
print("=== dict 结构 ===")
data1 = read_json_dict("config.json")
print(data1)
# 根是数组的JSON
print("\n=== list 结构 ===")
data2 = read_json_list("users.json")
# 抽取字段示例
if data2:
rows = extract_fields(data2, ["id", "name", "age", "city"])
print("抽取前3条:")
for r in rows[:3]:
print(r)
if __name__ == "__main__":
main()
代码讲解
json.load(f)直接从文件对象读,返回对应Python对象(dict或list)。json.loads(s)从字符串读,区别就是一个接文件一个接字符串。encoding="utf-8"必须指定,Windows默认GBK会读中文报错。- 根结构是
{}就是dict,是[]就是list,先type()判断一下再处理。 _get_nested支持点号路径取值,user.address.city这种嵌套字段不用一层一层.get()。
运行结果
控制台打印JSON的根类型、顶层key、记录条数。如果读的是 users.json,会把每条记录的指定字段抽出来打印前3条,准备好转CSV或做分析。
注意事项
- JSON里
null读进来是Python的None,true/false是True/False。 - 文件结尾多一个逗号、少个引号都会报
json.decoder.JSONDecodeError,先用在线JSON校验工具查一下。 - 超大JSON(几百MB)不要一次性load,考虑用
ijson流式解析。 - 中文默认不会变成
\uXXXX,因为文件是utf-8编码,读出来就是正常中文字符串。

更新时间:2026-09-14 20:55:49