第五章

Python 中的 JSON

学习 Python 中使用 JSON 的完整指南

Python json 模块

Python 内置了 json 模块,提供了完整的 JSON 编码和解码功能。

💡 导入模块:import json

序列化:Python 对象 → JSON

使用 json.dumps() 将 Python 对象转换为 JSON 字符串:

import json

# Python 字典
user = {
    "name": "张三",
    "age": 30,
    "skills": ["Python", "JavaScript"]
}

# 转换为 JSON 字符串
json_string = json.dumps(user)
print(json_string)
# 输出: {"name": "张三", "age": 30, "skills": ["Python", "JavaScript"]}

# 格式化输出(带缩进)
json_formatted = json.dumps(user, indent=2, ensure_ascii=False)
print(json_formatted)

常用参数

  • indent=n : 美化输出,n 为缩进空格数
  • ensure_ascii=False : 保留中文(默认转义为 Unicode)
  • sort_keys=True : 按键名排序

反序列化:JSON → Python 对象

使用 json.loads() 将 JSON 字符串转换为 Python 对象:

import json

# JSON 字符串
json_string = '{"name": "李四", "age": 28, "isStudent": true}'

# 转换为 Python 字典
user_obj = json.loads(json_string)
print(user_obj["name"])  # 输出: 李四
print(user_obj["age"])   # 输出: 28

类型对照表

JSON 类型

  • object → dict
  • array → list
  • string → str

Python 类型

  • number (int) → int
  • number (float) → float
  • true/false → True/False
  • null → None

文件操作

📖 读取 JSON 文件

import json

with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    print(data)

💾 写入 JSON 文件

import json

data = {"name": "张三", "age": 30}

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

实战案例:API 数据处理

获取 API 返回的 JSON 数据并处理:

import json
import requests

# 获取 API 数据
response = requests.get('https://api.example.com/users')
data = response.json()  # 自动解析 JSON

# 过滤数据
young_users = [u for u in data['users'] if u['age'] < 30]

# 保存到文件
with open('young_users.json', 'w', encoding='utf-8') as f:
    json.dump(young_users, f, ensure_ascii=False, indent=2)