JSON 数据处理
现代 Web 数据的标准格式
什么是 JSON?
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。
特点:
- 人类可读
- 机器易解析
- 广泛用于 API、Web 数据
结构类似 Python 字典:
json
{
"name": "Alice",
"age": 25,
"major": "Economics"
}基本操作
1. 导入模块
python
import json2. Python 对象 → JSON 字符串
python
import json
# Python 字典
data = {
'respondent_id': 1001,
'age': 30,
'income': 75000,
'interests': ['economics', 'data science']
}
# 转为 JSON 字符串
json_str = json.dumps(data, indent=2, ensure_ascii=False)
print(json_str)输出:
json
{
"respondent_id": 1001,
"age": 30,
"income": 75000,
"interests": [
"economics",
"data science"
]
}3. JSON 字符串 → Python 对象
python
json_str = '{"name": "Alice", "age": 25, "income": 50000}'
data = json.loads(json_str)
print(data['name']) # Alice
print(data['age']) # 254. 读写 JSON 文件
python
import json
# 写入文件
data = {'id': 1001, 'age': 30, 'income': 75000}
with open('respondent.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# 读取文件
with open('respondent.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(data)实战案例
案例 1:保存问卷数据
python
import json
survey_data = {
'survey_name': '2024 年收入调查',
'start_date': '2024-01-01',
'end_date': '2024-12-31',
'responses': [
{'id': 1001, 'age': 30, 'income': 75000},
{'id': 1002, 'age': 35, 'income': 85000},
{'id': 1003, 'age': 28, 'income': 65000}
],
'metadata': {
'region': '全国',
'sample_size': 1000,
'response_rate': 0.85
}
}
# 保存
with open('survey_2024.json', 'w', encoding='utf-8') as f:
json.dump(survey_data, f, indent=2, ensure_ascii=False)案例 2:从 API 获取 JSON 数据
python
import requests
import json
# 获取数据(示例 API)
response = requests.get('https://api.example.com/data')
# 解析 JSON
data = response.json() # 等价于 json.loads(response.text)
# 处理数据
for item in data['results']:
print(f"{item['name']}: {item['value']}")案例 3:JSON 与 Pandas 互转
python
import pandas as pd
import json
# Pandas → JSON
df = pd.DataFrame({
'id': [1, 2, 3],
'age': [25, 30, 35],
'income': [50000, 75000, 85000]
})
# 方法 1:转为 JSON 字符串
json_str = df.to_json(orient='records', force_ascii=False)
# 方法 2:直接保存文件
df.to_json('data.json', orient='records', indent=2, force_ascii=False)
# JSON → Pandas
df = pd.read_json('data.json')
print(df)orient 参数:
python
df.to_json(orient='records') # [{'col1': val1, 'col2': val2}, ...]
df.to_json(orient='index') # {'0': {'col1': val1}, '1': {...}}
df.to_json(orient='columns') # {'col1': {'0': val1, '1': val2}, ...}复杂 JSON 处理
嵌套 JSON
python
import json
# 复杂嵌套结构
data = {
'survey': {
'name': '收入调查',
'metadata': {
'year': 2024,
'region': '北京'
}
},
'respondents': [
{
'id': 1001,
'demographics': {
'age': 30,
'gender': 'Male'
},
'responses': {
'income': 75000,
'satisfaction': 4
}
}
]
}
# 访问嵌套数据
print(data['survey']['metadata']['year']) # 2024
print(data['respondents'][0]['demographics']['age']) # 30JSON Lines 格式(每行一个 JSON)
python
import json
# 写入 JSONL
respondents = [
{'id': 1001, 'age': 30},
{'id': 1002, 'age': 35},
{'id': 1003, 'age': 28}
]
with open('data.jsonl', 'w', encoding='utf-8') as f:
for resp in respondents:
f.write(json.dumps(resp, ensure_ascii=False) + '\n')
# 读取 JSONL
data = []
with open('data.jsonl', 'r', encoding='utf-8') as f:
for line in f:
data.append(json.loads(line))
print(f"读取了 {len(data)} 条记录")最佳实践
1. 处理中文
python
# 保留中文
json.dumps(data, ensure_ascii=False)
# 中文变为 \uXXXX
json.dumps(data, ensure_ascii=True)2. 美化输出
python
# 格式化(缩进2空格)
json.dumps(data, indent=2, ensure_ascii=False)3. 处理不可序列化的对象
python
from datetime import datetime
import json
# 日期对象无法直接序列化
data = {'date': datetime.now()}
# json.dumps(data) # TypeError
# 自定义序列化
def json_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
json_str = json.dumps(data, default=json_serializer)JSON vs CSV
| 特性 | JSON | CSV |
|---|---|---|
| 结构 | 嵌套结构 | 扁平表格 |
| 可读性 | 好 | 更好 |
| 文件大小 | 较大 | 较小 |
| 适用场景 | API、配置 | 表格数据 |
练习题
python
# 练习 1:配置文件
# 创建一个配置 JSON 文件,包含:
# - database: {host, port, username}
# - analysis: {min_age, max_age, sample_size}
# 保存并读取
# 练习 2:数据转换
# 读取 CSV 文件
# 转换为 JSON 格式(每行一个对象)
# 保存为 .json 和 .jsonl 两种格式Module 7 总结
你已经掌握:
- 文本文件读写
- CSV/Excel 处理
- Stata 文件读写
- JSON 数据处理
下一个模块:异常处理
继续!