JSON(JavaScript Object Notation)是 Web API 最常用的数据交换格式。pandas 可读写标准 JSON,以及每行一个 JSON 对象的 JSON Lines 格式。
1. read_json()
1.1 函数签名
pd.read_json(
path_or_buf=None, orient=None, typ='frame', dtype=None,
convert_axes=None, convert_dates=True, keep_default_dates=True,
numpy=False, precise_float=False, date_unit=None, encoding=None,
lines=False, chunksize=None, compression='infer', storage_options=None
)1.2 参数详解
| 参数 | 说明 |
|---|---|
path_or_buf | JSON 路径、文件对象或 JSON 字符串 |
orient | JSON 结构方向(见下表) |
typ | 返回类型:'frame' 或 'series' |
dtype | 列类型映射 |
convert_axes | 是否转换坐标轴(如果 True,还会尝试索引转换) |
convert_dates | 是否将日期列转为 datetime,格式为列名列表、布尔数组或字典 |
keep_default_dates | 是否自动检测索引中的日期 |
numpy | 直接使用 NumPy 解析(仅 orient='columns' 与 'records'),性能更好 |
precise_float | 使用高精度浮点解析 |
date_unit | 日期单位:'s'、'ms'、'us'、'ns' |
encoding | 文件编码 |
lines | 启用 JSON Lines(每行一个 JSON 对象) |
chunksize | 分块读取(lines=True 时) |
compression | 压缩格式 |
storage_options | 云存储配置 |
1.3 orient 参数说明
orient 决定了 JSON 与 DataFrame 之间的映射关系:
orient | JSON 结构 | 说明 |
|---|---|---|
'split' | {"columns": [...], "index": [...], "data": [...]} | 由列、索引、数据分开组成 |
'records' | [{"col1": v1, "col2": v2}, ...] | 记录列表(每行一个对象) |
'index' | {"row1": {"col1": v1}, ...} | 以索引为键、列为子对象 |
'columns' | {"col1": {"row1": v1}, ...} | 以列为键、索引为子对象(默认) |
'values' | [[v1, v2], [v3, v4]] | 纯值数组(无行列标签) |
'table' | 带 schema 的完整数据表结构 | 包含 schema 元数据 |
1.4 使用示例
import pandas as pd
# 读取 records 格式
df = pd.read_json('data.json', orient='records')
# 读取索引格式
df = pd.read_json('data.json', orient='index')
# JSON Lines 格式(每行一个 JSON 对象)
df = pd.read_json('data.jsonl', lines=True)
# 分块读取大 JSON Lines
reader = pd.read_json('data.jsonl', lines=True, chunksize=1000)
# 从字符串读取
df = pd.read_json('{"A": [1, 2, 3], "B": [4, 5, 6]}')2. to_json()
2.1 函数签名
DataFrame.to_json(
path_or_buf=None, orient=None, date_format='epoch',
double_precision=10, force_ascii=True, date_unit='ms',
default_handler=None, lines=False, compression='infer',
index=True, indent=None, storage_options=None
)2.2 参数详解
| 参数 | 说明 |
|---|---|
path_or_buf | 写出路径、文件对象,None 返回 JSON 字符串 |
orient | 与 read_json 相同('split'、'records'、'index'、'columns'、'values'、'table') |
date_format | 日期格式:'epoch'(时间戳)或 'iso'(ISO 8601) |
double_precision | 浮点精度(小数点后位数) |
force_ascii | 是否强制转义非 ASCII 字符(默认 True) |
date_unit | 日期时间戳单位:'s'、'ms'、'us'、'ns' |
default_handler | 处理不可序列化对象的函数 |
lines | 输出 JSON Lines 格式(每个对象为一行) |
compression | 压缩格式 |
index | 是否写出索引 |
indent | 缩进空格数(用于美化输出) |
storage_options | 云存储配置 |
2.3 使用示例
# 写出为 records 格式
df.to_json('output.json', orient='records')
# 写出为分列格式,日期为 ISO
df.to_json('output.json', orient='columns', date_format='iso')
# 美化缩进并保留中文
df.to_json('output.json', indent=2, force_ascii=False)
# JSON Lines
df.to_json('output.jsonl', orient='records', lines=True)
# 返回字符串
s = df.to_json(orient='split')3. json_normalize()
用于将嵌套 JSON(列表中的字典、字典中的字典)扁平化为二维表格。pandas 2.2+ 推荐使用
pd.json_normalize替代已弃用的DataFrame.from_records(...).json_normalize()方式。
3.1 函数签名
pd.json_normalize(
data, record_path=None, meta=None, meta_prefix=None,
record_prefix=None, errors='raise', sep='.', max_level=None
)3.2 参数详解
| 参数 | 说明 |
|---|---|
data | 字典、列表或 JSON 字符串 |
record_path | 需要扁平化的嵌套列表路径 |
meta | 需要留在外层的字段(元数据字段) |
meta_prefix | 元数据字段的前缀 |
record_prefix | 记录字段的前缀 |
errors | 元数据错误处理:'raise' 或 'ignore' |
sep | 嵌套字段的连接符(默认 ',') |
max_level | 最大扁平化层级 |
3.3 使用示例
import pandas as pd
data = [
{
'id': 1,
'name': '张三',
'orders': [
{'order_id': 101, 'amount': 50},
{'order_id': 102, 'amount': 30}
]
},
{
'id': 2,
'name': '李四',
'orders': [
{'order_id': 103, 'amount': 80}
]
}
]
# 扁平化 orders 列表,保留 id 和 name
df = pd.json_normalize(
data,
record_path='orders',
meta=['id', 'name']
)
# 输出:
# order_id amount id name
# 0 101 50 1 张三
# 1 102 30 1 张三
# 2 103 80 2 李四4. build_table_schema()
生成 DataFrame 的 JSON Table Schema 描述,可配合
orient='table'使用。
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': ['x', 'y']})
schema = pd.io.json.build_table_schema(df)
print(schema){
"fields": [
{"name": "index", "type": "integer"},
{"name": "A", "type": "integer"},
{"name": "B", "type": "string"}
],
"primaryKey": ["index"],
"pandas_version": "2.3.3"
}文档 4:4.3 HTML 与 XML.md