JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,被广泛用于网络通信、配置文件和数据存储。
它以纯文本形式保存结构化数据,既简洁又通用,几乎所有编程语言(包括 Python)都能原生解析。
在 Python 的数据世界中,JSON 是最自然的语言,它既像字典(dict),又像文件(file),既能直接表示结构,又能方便地持久化保存。
文件扩展名: .json
推荐编码: UTF-8(跨平台通用)
一、JSON 格式的基本特性
JSON 数据由两种基本结构组成:
1、对象(Object):由一组键值对(key-value)构成,键必须是字符串。
json
{"name": "Alice", "age": 25}
2、数组(Array):用中括号 [] 表示的有序数据集合。
cs
[1, 2, 3]
其他数据类型还有字符串、数字、布尔值、空值(null)等。
JSON 整体语法规则简洁、可嵌套、可跨语言通用。
二、Python 与 JSON 的数据映射关系
JSON 与 Python 的数据类型几乎一一对应,使得 JSON 与 Python 数据结构之间的互操作非常自然,非常利于序列化(Python → JSON)与反序列化(JSON → Python)操作。
| JSON 数据类型 | Python 对应类型 | 示例说明 |
|---|---|---|
| 对象(object) | 字典(dict) | {"name": "小艾", "age": 18} → {"name": "小艾", "age": 18} |
| 数组(array) | 列表(list) | [1, 2, 3] → ``[1, 2, 3] |
| 字符串(string) | 字符串(str) | "hello" → ``'hello' |
| 数字(number) | 整数或浮点数(int/float) | 42 → 42 3.14 → 3.14 |
| true / false / null | True / False / None | true → True false → False null → None |
示例:类型映射演示
bash
import json
# 构造 JSON 文本json_text = """{ "name": "小艾", "age": 18, "score": 92.5, "hobbies": ["reading", "cycling", "music"], "married": false, "children": null}"""
# 反序列化(JSON → Python)data = json.loads(json_text)print("JSON 转 Python:")print(type(data), "→", data)print()
# 验证各类型映射print("name:", data["name"], type(data["name"])) # strprint("age:", data["age"], type(data["age"])) # intprint("score:", data["score"], type(data["score"])) # floatprint("hobbies:", data["hobbies"], type(data["hobbies"])) # listprint("married:", data["married"], type(data["married"])) # boolprint("children:", data["children"], type(data["children"])) # NoneType
# 序列化(Python → JSON)json_back = json.dumps(data, ensure_ascii=False, indent=2)print("\nPython 转 JSON:")print(json_back)
输出示例:
javascript
JSON 转 Python:<class 'dict'> → {'name': '小艾', 'age': 18, 'score': 92.5, 'hobbies': ['reading', 'cycling', 'music'], 'married': False, 'children': None}
name: 小艾 <class 'str'>age: 18 <class 'int'>score: 92.5 <class 'float'>hobbies: ['reading', 'cycling', 'music'] <class 'list'>married: False <class 'bool'>children: None <class 'NoneType'>
Python 转 JSON:{ "name": "小艾", "age": 18, "score": 92.5, "hobbies": [ "reading", "cycling", "music" ], "married": false, "children": null}
说明:
• json.loads():将 JSON 字符串解析为 Python 对象。
• json.dumps():将 Python 对象转为 JSON 字符串。
• ensure_ascii=False:防止中文被转义为 \uXXXX。
• indent=2:输出带缩进的易读格式(缩进 2 个空格)。
三、读取 JSON 文件
使用 json.load() 方法,可以直接将文件内容解析为 Python 对象。
python
import json
# 读取 JSON 文件内容with open("data.json", "r", encoding="utf-8") as f: data = json.load(f)
print(data)
说明:
• json.load(f) 会自动解析文件中的 JSON 数据。
• 参数是文件对象(区别于 loads() 的字符串输入)。
• 解析结果类型取决于文件结构:对象 → 字典、数组 → 列表。
四、写入 JSON 文件
1、将 Python 对象写入 JSON 文件
使用 json.dump() 方法,可以将 Python 对象写入 JSON 文件。
python
import json
data = { "project": "AI Report", "version": 1.0, "completed": True, "members": ["Alice", "Bob", "Charlie"]}
# 写入 JSON 文件with open("report.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=4)
说明:
• ensure_ascii=False:允许写入中文字符。
• indent=4:表示以 4 个空格缩进,生成更易读的格式。
• Python 会自动将字典转换为 JSON 对象。
2、更新 JSON 文件内容
更新 JSON 的流程是:读取 → 修改 → 写回。
python
import json
# 读取原文件with open("report.json", "r", encoding="utf-8") as f: config = json.load(f)
# 修改数据config["version"] = 2.0config["members"] = ["小艾", "小包", "小咖"]
# 写回文件with open("report.json", "w", encoding="utf-8") as f: json.dump(config, f, ensure_ascii=False, indent=4)
应用场景:
常用于配置文件(config.json)、应用设置、版本管理等。
3、在内存中生成 JSON(使用 StringIO)
使用 io.StringIO() 可以在内存中构建 JSON 字符串,而不写入硬盘文件。
python
from io import StringIOimport json
buffer = StringIO()data = {"language": "Python", "topic": "JSON 操作", "level": "基础"}
json.dump(data, buffer, ensure_ascii=False, indent=2)
# 获取内存中的 JSON 内容json_content = buffer.getvalue()print(json_content)
说明:
• StringIO 提供"类文件"对象,可像文件一样使用。
• 适用于临时数据生成、API 响应模拟或内存数据缓存。
五、异常与安全性处理
JSON 文件解析失败或不存在时,会抛出异常。应在程序中进行捕获,保证程序稳定运行。
python
import json
try: with open("data.json", "r", encoding="utf-8") as f: data = json.load(f) print(data)except json.JSONDecodeError as e: print("JSON 格式错误:", e)except FileNotFoundError: print("文件未找到!")
说明:
• json.JSONDecodeError:JSON 内容格式错误。
• FileNotFoundError:目标文件不存在。
• 建议在生产代码中始终加入异常捕获。
六、应用实例:学生成绩管理
下面的示例演示了如何使用 JSON 存储和读取学生成绩。
python
import json
students = [ {"name": "小艾", "score": 92}, {"name": "小包", "score": 85}, {"name": "小咖", "score": 78}]
# 写入 JSON 文件with open("scores.json", "w", encoding="utf-8") as f: json.dump(students, f, ensure_ascii=False, indent=2)
# 读取 JSON 文件with open("scores.json", "r", encoding="utf-8") as f: data = json.load(f)
# 输出结果for student in data: print(f"{student['name']} 的成绩:{student['score']}")
输出:
go
小艾 的成绩:92小包 的成绩:85小咖 的成绩:78
📘 小结
JSON 是结构化数据的理想存储格式,具有以下优势:
🔹与 Python 的 dict、list 结构天然兼容。
🔹支持文件与字符串两种读写方式。
🔹格式轻量,适合网络传输。
🔹可读性高,易于人类与机器共享。
🔹适用于配置文件、日志、数据接口等多场景。
在 Python 文件操作中,JSON 是最常用、最通用的格式之一。
掌握 json.load()、json.dump()、json.loads()、json.dumps() 四个核心函数,即可完成从内存结构到可交换文件的高效转换。

"点赞有美意,赞赏是鼓励"