4.4 Python3 JSON模块

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,Python 提供了 json 模块来处理 JSON 数据。


目录

1. JSON 基本操作

1.1 导入模块

1.2 Python 对象与 JSON 转换

2. 常用方法

2.1 json.dumps() - 将 Python 对象编码为 JSON 字符串

2.2 json.loads() - 将 JSON 字符串解码为 Python 对象

3. 文件读写

3.1 json.dump() - 将 Python 对象写入 JSON 文件

3.2 json.load() - 从 JSON 文件读取数据

4. 高级用法

4.1 处理日期时间对象

4.2 自定义解码器

5. JSON 与 CSV 转换示例

6. 注意事项

7. 性能优化


1. JSON 基本操作

1.1 导入模块

import json

1.2 Python 对象与 JSON 转换

Python 类型JSON 类型
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull

2. 常用方法

2.1 json.dumps() - 将 Python 对象编码为 JSON 字符串

import json

data = {
    "name": "张三",
    "age": 30,
    "is_student": False,
    "courses": ["数学", "英语"],
    "address": None
}

json_str = json.dumps(data, ensure_ascii=False, indent=4)
print(json_str)

参数说明:

  • ensure_ascii=False: 允许非ASCII字符(如中文)正常显示

  • indent=4: 美化输出,缩进4个空格

2.2 json.loads() - 将 JSON 字符串解码为 Python 对象

import json

json_data = '''
{
    "name": "李四",
    "age": 25,
    "is_student": true,
    "courses": ["物理", "化学"],
    "address": null
}
'''

python_obj = json.loads(json_data)
print(python_obj["name"])  # 输出: 李四

3. 文件读写

3.1 json.dump() - 将 Python 对象写入 JSON 文件

import json

data = {
    "product": "手机",
    "price": 3999.99,
    "in_stock": True,
    "specs": {"RAM": "8GB", "Storage": "256GB"}
}

with open('product.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

3.2 json.load() - 从 JSON 文件读取数据

import json


with open('product.json', 'r', encoding='utf-8') as f:
    product_data = json.load(f)
    print(product_data["product"])  # 输出: 手机


4. 高级用法

4.1 处理日期时间对象

import json
from datetime import datetime

def datetime_encoder(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError("Type not serializable")

now = datetime.now()
data = {"time": now, "message": "当前时间"}

json_str = json.dumps(data, default=datetime_encoder, ensure_ascii=False)
print(json_str)  # {"time": "2025-06-15T14:30:00.123456", "message": "当前时间"}

4.2 自定义解码器

import json
from datetime import datetime

def datetime_decoder(dct):
    if "time" in dct:
        try:
            # 返回整个字典,但将time字段转换为datetime对象
            dct["time"] = datetime.fromisoformat(dct["time"])
            return dct
        except ValueError:
            pass
    return dct

json_data = '{"time": "2023-03-15T14:30:00"}'
result = json.loads(json_data, object_hook=datetime_decoder)
print(type(result["time"]))  # 输出 <class 'datetime.datetime'>


5. JSON 与 CSV 转换示例

import json
import csv

# JSON 转 CSV
def json_to_csv(json_file, csv_file):
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    if isinstance(data, list):
        with open(csv_file, 'w', encoding='utf-8', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=data[0].keys())
            writer.writeheader()
            writer.writerows(data)

# 使用示例
data = [
    {"name": "张三", "age": 25},
    {"name": "李四", "age": 30}
]
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False)

json_to_csv('data.json', 'data.csv')


6. 注意事项

  1. JSON 的键必须是字符串类型(Python 中为 str)

  2. JSON 不支持 Python 的 set 类型,可以转换为 list

  3. 处理大量数据时考虑使用 ijson 等流式解析库

  4. 从不可信来源加载 JSON 时存在安全风险,可使用 json.JSONDecodeError 捕获异常

  5. 默认情况下 JSON 不保留字典的插入顺序(Python 3.7+ 中字典已有序)


7. 性能优化

对于大型 JSON 数据:

import json
import orjson
# 使用 orjson 替代 json(更快,但需要安装)
# pip install orjson

# 使用生成器处理大型数组
def stream_json_array(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            yield json.loads(line)



data = {"key": "value"}
json_bytes = orjson.dumps(data)  # 返回 bytes 而不是 str
python_obj = orjson.loads(json_bytes)

JSON 是 Python 中数据交换的标准格式,掌握这些技巧可以高效处理各种数据交互场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值