Pandas df.to_json() Function
to_json() It is a DataFrame method used to export data to JSON (JavaScript Object Notation) format.
JSON is the standard format for data exchange in web applications and APIs,to_json() it supports multiple JSON output formats, including record, index, and column formats. It can convert a pandas DataFrame to a JSON string or write it to a file, facilitating data exchange with other systems.
Basic syntax and parameters
Syntax format
DataFrame.to_json(path_or_buf=None, orient=None, date_format=None,
double_precision=10, force_ascii=True, date_unit='ms',
default_handler=None, lines=False, index=False,
indent=None, ...)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| path_or_buf | str, path object, file-like object | File path; if None, return a string | None |
| orient | str | JSON formats: 'split', 'records', 'index', 'columns', 'values', 'table' | None |
| date_format | str | Date formats: 'epoch', 'iso' | None |
| double_precision | int | Floating-point precision | 10 |
| force_ascii | bool | Whether to force ASCII encoding | True |
| date_unit | str | Date units: 's', 'ms', 'us', 'ns' | 'ms' |
| lines | bool | JSON Lines format, one JSON object per line | False |
| index | bool | Whether to include the index | False |
Return Value
- Return Type:
Noneorstr - When a file path is specified, write to the file and return None.
- When
path_or_buf=None, return a JSON-formatted string.
Example
Through the following examples, fully master to_json() its various usages.
Example 1: Basic Usage - Exporting to a JSON String
First create a DataFrame, then use to_json() Export to JSON format.
Example
import
pandas
as
pd
Create a sample DataFrame
data
=
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
]
,
'age'
:
[
28
,
35
,
42
,
26
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
,
'salary'
:
[
8000
,
12000
,
15000
,
7000
]
}
df
=
pd.
DataFrame
(
data
)
Example 1a: The most basic export (no path specified, returns a string)
Default orient='columns'
json_string
=
df.
to_json
(
)
(
"Default JSON format (columns):"
)
(
json_string
)
(
)
Example 1b: Exporting to a file
df.
to_json
(
'output_basic.json'
,
orient
=
'records'
,
indent
=
2
)
(
"Exported to output_basic.json"
)
Read back to verify
df_check
=
pd.
read_json
(
'output_basic.json'
,
orient
=
'records'
)
(
"nVerify read:"
)
(
df_check
)
Expected output:
默认 JSON 格式 (columns):
{"name":{"0":"Tom","1":"Jerry","2":"Mike","3":"Lucy"},"age":{"0":28,"1":35,"2":42,"3":26},...}
默认 JSON 格式 (records):
[
{"name":"Tom","age":28,"city":"Beijing","salary":8000},
{"name":"Jerry","age":35,"city":"Shanghai","salary":12000},
{"name":"Mike","age":42,"city":"Guangzhou","salary":15000},
{"name":"Lucy","age":26,"city":"Shenzhen","salary":7000}
]
Code analysis:
to_json()Returns a JSON string when no path is specified.- Default
orient='columns', one JSON object per column. indent=2Make the output more readable (formatted).
Example 2: Different JSON Formats
JSON data comes in multiple formats,to_json() it supports multiple output formats to meet different needs.
Example
import
pandas
as
pd
Create DataFrame
df
=
pd.
DataFrame
(
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
]
,
'age'
:
[
28
,
35
,
42
,
26
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
}
)
Example 2a: records format - array format, one object per row
Most commonly used, suitable for most APIs
json_records
=
df.
to_json
(
orient
=
'records'
)
(
"Records format (one object per row):"
)
(
json_records
)
(
)
Example 2b: index format - using the index as keys
json_index
=
df.
to_json
(
orient
=
'index'
)
(
"Index format (index as keys):"
)
(
json_index
)
(
)
Example 2c: columns format - using column names as keys (default)
json_columns
=
df.
to_json
(
orient
=
'columns'
)
(
"Columns format (column names as keys):"
)
(
json_columns
)
(
)
Example 2d: split format - separated structure
json_split
=
df.
to_json
(
orient
=
'split'
)
(
"Split format (separated structure):"
)
(
json_split
)
(
)
Example 2e: values format - contains only the values array
json_values
=
df.
to_json
(
orient
=
'values'
)
(
"Values format (values only):"
)
(
json_values
)
Expected output:
Records 格式(每行一个对象):
[{"name":"Tom","age":28,"city":"Beijing"},
{"name":"Jerry","age":35,"city":"Shanghai"},
{"name":"Mike","age":42,"city":"Guangzhou"},
{"name":"Lucy","age":26,"city":"Shenzhen"}]
Index 格式(以索引为键):
{"0":{"name":"Tom","age":28,"city":"Beijing"},
"1":{"name":"Jerry","age":35,"city":"Shanghai"},
...}
Columns 格式(以列名为键):
{"name":{"0":"Tom","1":"Jerry"...},"age":{"0":28...}...}
Split 格式(分离结构):
{"index":[0,1,2,3],"columns":["name","age","city"],
"data":[["Tom",28,"Beijing"],["Jerry",35,"Shanghai"]...]}
Values 格式(只包含值):
[["Tom",28,"Beijing"],["Jerry",35,"Shanghai"],["Mike",42,"Guangzhou"],["Lucy",26,"Shenzhen"]]
Code analysis:
orient='records': array format, where each row is a JSON object; most commonly used.orient='index': uses the DataFrame index as top-level keys.orient='columns': uses column names as keys; the default format.orient='split': a separated structure, easy for programs to parse.orient='values': a pure numeric array, with no column names or index.
Example 3: Handling Dates and Chinese Encoding
When exporting to JSON, dates and Chinese encoding must be handled correctly.
Example
import
pandas
as
pd
from
datetime
import
datetime
Example 3a: Handling date fields
df_date
=
pd.
DataFrame
(
{
'name'
:
[
'Tom'
,
'Jerry'
]
,
'birthday'
:
[
datetime
(
1995
,
3
,
15
)
,
datetime
(
1988
,
7
,
22
)
]
,
'join_date'
:
[
datetime
(
2020
,
1
,
10
)
,
datetime
(
2019
,
3
,
5
)
]
}
)
The default date format is a timestamp (milliseconds)
json_timestamp
=
df_date.
to_json
(
date_format
=
'epoch'
,
orient
=
'records'
)
(
"Date format - timestamp:"
)
(
json_timestamp
)
(
)
ISO format dates
json_iso
=
df_date.
to_json
(
date_format
=
'iso'
,
orient
=
'records'
)
(
"Date format - ISO:"
)
(
json_iso
)
(
)
Example 3b: Handling Chinese
df_cn
=
pd.
DataFrame
(
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
]
,
'Age'
:
[
28
,
35
,
42
]
,
'City'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
]
}
)
force_ascii=False allows non-ASCII characters
json_cn
=
df_cn.
to_json
(
orient
=
'records'
,
force_ascii
=
False
)
(
"Chinese content (force_ascii=False):"
)
(
json_cn
)
Write to file (Chinese supported by default)
df_cn.
to_json
(
'output_cn.json'
,
orient
=
'records'
,
force_ascii
=
False
)
(
"nExported to output_cn.json"
)
Read back to verify
df_cn_check
=
pd.
read_json
(
'output_cn.json'
)
(
"Verify read:"
)
(
df_cn_check
)
Expected output:
Date format - Timestamp:
[{"name":"Tom","birthday":796...
{"name":"Jerry","birthday":584...}
日期格式 - ISO:
[{"name":"tom","birthday":"1995-03-15T00:00:00.000Z",...}]
中文内容(force_ascii=False):
[{"姓名":"张三","年龄":28,"城市":"北京"},
{"姓名":"李四","年龄":35,"城市":"上海"},
{"姓名":"王五","年龄":42,"城市":"广州"}]
已导出到 output_cn.json
Verify reading:
姓名 年龄 城市
0 张三 (read_json 的 格式 orient='records' 匹配 to_json 的 orient='records') 北京
1 配对 李四 35 上海
2 王五 42 广州
Code analysis:
date_format='epoch'Convert dates to timestamps (milliseconds).date_format='iso'Convert dates to ISO 8601 format.force_ascii=FalseAllows Chinese characters to be preserved in JSON instead of being escaped as Unicode.
Example 4: JSON Lines Format
JSON Lines is a format with one JSON object per line, commonly used in logging and big data processing.
Example
import
pandas
as
pd
Create DataFrame
df
=
pd.
DataFrame
(
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
]
,
'age'
:
[
28
,
35
,
42
,
26
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
}
)
Example 4a: JSON Lines format (one JSON object per line)
lines=True enables JSON Lines format
json_lines
=
df.
to_json
(
orient
=
'records'
,
lines
=
True
)
(
"JSON Lines format:"
)
(
json_lines
)
(
)
Writing to a File
df.
to_json
(
'output_lines.json'
,
orient
=
'records'
,
lines
=
True
)
(
"Exported to output_lines.json"
)
Example 4b: Reading JSON Lines format
Need to read line by line
import
json
df_lines_list
=
[
]
with
open
(
'output_lines.json'
,
'r'
,
encoding
=
'utf-8'
)
as
f:
for
line
in
f:
df_lines_list.
append
(
json.
loads
(
line.
strip
(
)
)
)
df_from_lines
=
pd.
DataFrame
(
df_lines_list
)
(
"nReading JSON Lines:"
)
(
df_from_lines
)
Expected output:
JSON Lines 格式:
{"name":"Tom","age":28,"city":"Beijing"}
{"name":"Jerry","age":35,"city":"Shanghai"}
{"name":"Mike","age":42,"city":"city":"Guangzhou"}
{"name":"Lucy","age":26,"city":"Shenzhen"}
已导出到 output_lines.json
读取 JSON Lines:
name age city
0 Tom 28 Beijing
对 读 Jerry 35 Shanghai
2 Mike 42 格式 Guangzhou
3 Lucy 26 Shenzhen
Code analysis:
lines=TrueEnables JSON Lines format, one JSON object per line.- JSON Lines is suitable for streaming processing and big data scenarios.
- When reading, parse line by line and convert to a DataFrame.
Notes
- Default
orient='columns', generally it is recommended to useorient='records'which is more general. - Use
force_ascii=FalseIt can preserve Chinese characters. - JSON Lines format needs to be used with
orient='records'. read_json()When reading, you need to use the sameorientparameter was added.- For date format, it is recommended to use
date_format='iso', which is more readable.
Summary
to_json() It is the core method for exporting a DataFrame to JSON format. It supports multiple JSON formats and can meet the needs of different scenarios such as Web APIs and data exchange.
In practice, JSON is the most commonly used data format for web applications,to_json() together with read_json() enabling data import and export. Readers are advised to focus on mastering orient the different formats of the parameter, and its read_json() paired usage.
Common Pandas functions