JSON(JavaScript Object Notation)是一种轻量级的数据交换格式(lightweight data interchange format)
常用于 Web 应用、配置文件(configuration files,)和数据通信
本文将介绍如何使用 Python 内置的 json 模块,实现(Implement)字典与 JSON 字符串的转换、文件的读写,以及在实际案例中处理数据(in practical cases)
1. 什么是 JSON?
JSON 是一种基于文本(text-based)的格式,用来表示结构化数据(represent structured data),易于人阅读和编写,同时也易于机器解析和生成。
2. Python 中的 json 模块
Python 提供了内置的 json 模块
无需额外安装(without additional installation)——
即可完成数据的序列化(serialization)(转换成 JSON 字符串)与反序列化(deserialization)(解析 JSON 字符串)。
2.1 字典与 JSON 字符串转换 (Dictionary <-> JSON String)
示例:
import json
data = {
"name": "梓豪",
"age": 25,
"city": "青岛"
}
# 将字典转换为 JSON 字符串 (Serialize)
json_str = json.dumps(data, indent=4, ensure_ascii=False)
print("JSON 字符串:")
print(json_str)
# 将 JSON 字符串转换回字典 (Deserialize)
data_back = json.loads(json_str)
print("还原的字典:", data_back)
说明:
- json.dumps() 将 Python 对象转换为 JSON 字符串
- 参数 indent=4 用于格式化输出,ensure_ascii=False 保证中文不被转义(been not escaped)
3. 文件操作:读写 JSON 文件
通过文件读写,可以将 JSON 数据存储到磁盘或从磁盘加载数据。
3.1 写入 JSON 到文件
import json
orders = {
"订单": [
{"订单号": 101, "顾客": "梓涵", "total": 120},
{"订单号": 102, "顾客": "梓萱", "total": 80}
]
}
with open("orders.json", "w", encoding="utf-8") as f:
json.dump(orders, f, indent=4, ensure_ascii=False)
说明:
- 使用 json.dump() 直接将数据写入文件,with 语句确保文件自动关闭
3.2 从文件读取 JSON
import json
with open("orders.json", "r", encoding="utf-8") as f:
orders_data = json.load(f)
print("加载的订单数据:")
print(orders_data)
说明:
- json.load() 从文件中读取并解析 JSON 数据,生成相应的 Python 对象。
4. 实际案例:处理生活订单数据
假设你经营一家小店,存储了订单信息的 JSON 数据,我们可以用以下代码遍历订单并给出消费建议。
import json
orders_json = '''
{
"orders": [
{"order_id": 1, "customer": "诗涵", "total": 45},
{"order_id": 2, "customer": "雨桐", "total": 75},
{"order_id": 3, "customer": "宇轩", "total": 30}
]
}
'''
orders_data = json.loads(orders_json) #转换为 Python 字典
for order in orders_data["orders"]:
if order["total"] > 50:
advice = "消费较高,送积分奖励!"
else:
advice = "消费一般,欢迎下次光临!"
print(f"订单 {order['order_id']} 的客户 {order['customer']}:{order['total']} 元 -> {advice}")
5. 小贴士与注意事项 (Tips & Caveats)
- ensure_ascii=False:保证输出中文时不会转义为 Unicode。
- indent 参数:使生成的 JSON 更加美观易读(readable)
- 区分 json.dumps 与 json.dump:前者返回字符串,后者直接写入文件。
- 异常处理:处理文件读写时建议加上异常捕获,防止文件不存在或格式错误。
(use try-except blocks for file operations to handle errors gracefully.)