pandas.DataFrame.to_json按行转json的方法

山间有风
山间有风
发布时间:2026-10-13| 6人浏览过
原创

本文介绍如何使用pandas.DataFrame.to_json方法将数据框转换为JSON格式。重点讲解orient参数,特别是records选项如何实现按行转换,生成[{column -> value}, ...]格式的列表,适用于前端展示等场景。

近期工作中遇到需求,需将CSV文件读取为DataFrame,并以JSON格式输出至前端展示,因此涉及使用DataFrame的to_json方法。

to_json方法默认以列名为键、列内容为值,生成类似{col1:[v11,v21,v31…],col2:[v12,v22,v32],…}的结构。但有时需要按行转换为JSON,格式如[row1:{col1:v11,col2:v12,col3:v13…},row2:{col1:v21,col2:v22,col3:v23…}]。

查阅官方文档可知,to_json方法包含orient参数,其说明如下:

orient : string 
Series 
default is ‘index' 
allowed values are: {‘split','records','index'} 
DataFrame 
default is ‘columns' 
allowed values are: {‘split','records','index','columns','values'} 
The format of the JSON string 
split : dict like {index -> [index], columns -> [columns], data -> [values]} 
records : list like [{column -> value}, … , {column -> value}] 
index : dict like {index -> {column -> value}} 
columns : dict like {column -> {index -> value}} 
values : just the values array 
table : dict like {‘schema': {schema}, ‘data': {data}} describing the data, and the data component is like orient='records'. 
Changed in version 0.20.0

具体含义为:

若对Series进行JSON转换,默认orient为'index',可选参数包括{‘split','records','index'}。

若对DataFrame进行JSON转换,默认orient为'columns',可选参数包括{‘split','records','index','columns','values'}。

各orient参数对应的JSON格式如下:

split格式为{index -> [index], columns -> [columns], data -> [values]}。

records格式为[{column -> value}, … , {column -> value}]。

index格式为{index -> {column -> value}}。

columns格式为{column -> {index -> value}}。

values仅输出值数组。

table格式为{‘schema': {schema}, ‘data': {data}},与records类似。

参考官方示例:

df = pd.DataFrame([['a', 'b'], ['c', 'd']],
  index=['row 1', 'row 2'],
  columns=['col 1', 'col 2'])
###########
split
###########
df.to_json(orient='split')
>'{"columns":["col 1","col 2"],
 "index":["row 1","row 2"],
 "data":[["a","b"],["c","d"]]}'
###########
index
###########
df.to_json(orient='index')
>'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
###########
records
###########
df.to_json(orient='index')
>'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
###########
table
###########
df.to_json(orient='table')
>'{"schema": {"fields": [{"name": "index", "type": "string"},
  {"name": "col 1", "type": "string"},
  {"name": "col 2", "type": "string"}],
 "primaryKey": "index",
 "pandas_version": "0.20.0"},
 "data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
 {"index": "row 2", "col 1": "c", "col 2": "d"}]}'

主要参考官方API文档:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html

以上即为pandas.DataFrame.to_json按行转换JSON的方法分享,希望提供有用参考,欢迎支持。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。