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_bufJSON 路径、文件对象或 JSON 字符串
orientJSON 结构方向(见下表)
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 之间的映射关系:

orientJSON 结构说明
'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