Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas df.to_json() Function

Pandas df.to_json() Function

Pandas Common Functions Common Pandas functions


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


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

(

)

print

(

"Default JSON format (columns):"

)

print

(

json_string

)

print

(

)

Example 1b: Exporting to a file

df.

to_json

(

'output_basic.json'

,

orient

=

'records'

,

indent

=

2

)

print

(

"Exported to output_basic.json"

)

Read back to verify

df_check

=

pd.

read_json

(

'output_basic.json'

,

orient

=

'records'

)

print

(

"nVerify read:"

)

print

(

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:

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'

)

print

(

"Records format (one object per row):"

)

print

(

json_records

)

print

(

)

Example 2b: index format - using the index as keys

json_index

=

df.

to_json

(

orient

=

'index'

)

print

(

"Index format (index as keys):"

)

print

(

json_index

)

print

(

)

Example 2c: columns format - using column names as keys (default)

json_columns

=

df.

to_json

(

orient

=

'columns'

)

print

(

"Columns format (column names as keys):"

)

print

(

json_columns

)

print

(

)

Example 2d: split format - separated structure

json_split

=

df.

to_json

(

orient

=

'split'

)

print

(

"Split format (separated structure):"

)

print

(

json_split

)

print

(

)

Example 2e: values format - contains only the values array

json_values

=

df.

to_json

(

orient

=

'values'

)

print

(

"Values format (values only):"

)

print

(

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:

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'

)

print

(

"Date format - timestamp:"

)

print

(

json_timestamp

)

print

(

)

ISO format dates

json_iso

=

df_date.

to_json

(

date_format

=

'iso'

,

orient

=

'records'

)

print

(

"Date format - ISO:"

)

print

(

json_iso

)

print

(

)

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

)

print

(

"Chinese content (force_ascii=False):"

)

print

(

json_cn

)

Write to file (Chinese supported by default)

df_cn.

to_json

(

'output_cn.json'

,

orient

=

'records'

,

force_ascii

=

False

)

print

(

"nExported to output_cn.json"

)

Read back to verify

df_cn_check

=

pd.

read_json

(

'output_cn.json'

)

print

(

"Verify read:"

)

print

(

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:

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

)

print

(

"JSON Lines format:"

)

print

(

json_lines

)

print

(

)

Writing to a File

df.

to_json

(

'output_lines.json'

,

orient

=

'records'

,

lines

=

True

)

print

(

"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

)

print

(

"nReading JSON Lines:"

)

print

(

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:


Notes


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.

Pandas Common Functions Common Pandas functions