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

Pandas pd.read_json() function

Pandas pd.read_json() function

Python math Module Common Pandas functions


read_json() is a function in the pandas library for reading JSON (JavaScript Object Notation) files; it supports importing data in multiple JSON formats.

JSON is a lightweight data exchange format that is easy for humans to read and write and easy for machines to parse and generate. It is widely used in Web APIs, configuration files, and similar scenarios.read_json() can convert JSON data into a pandas DataFrame for convenient data analysis.


Basic syntax and parameters

Syntax format



pandas.read_json(path_or_buf, orient=None, typ='frame', dtype=None,

                convert_axes=None, convert_dates=True, keep_default_dates=True,

                numpy=False, precise_float=False, date_unit='ms', ...)

Parameter Description

Parameters Type Description Default value
path_or_buf str, path object, or file-like object a JSON file path, URL, or string Required
orient str the format of the JSON data: 'split', 'records', 'index', 'columns', 'values' None
typ str the return type: 'frame' returns a DataFrame, 'series' returns a Series 'frame'
dtype dict specify the data types of columns None
convert_axes bool whether to convert axes to dates/times None
convert_dates bool, list whether to convert date columns True
numpy bool whether to use numpy arrays False

Return Value


Example

Through the following examples, fully master read_json() its various usages.

Example 1: read JSON data in different formats

JSON data comes in multiple formats,read_json() supports the most common formats.

Example

import

pandas

as

pd

import

json

sample data: JSON array format (records format)

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}
]
'''

Write the JSON string to a file

with

open

(

'data_records.json'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

json_records

)

Read the JSON file (records format, the most common)

orient='records' means each row is a JSON object

df_records

=

pd.

read_json

(

'data_records.json'

,

orient

=

'records'

)

print

(

"Records format:"

)

print

(

df_records

)

print

(

)

sample data: JSON object format (index format)

json_index

=

'''
{
    "Tom": {"age": 28, "city": "Beijing", "salary": 8000},
    "Jerry": {"age": 35, "city": "Shanghai", "salary": 12000},
    "Mike": {"age": 42, "city": "Guangzhou", "salary": 15000}
}
'''

with

open

(

'data_index.json'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

json_index

)

Read the JSON file (index format, using a field as the index)

df_index

=

pd.

read_json

(

'data_index.json'

,

orient

=

'index'

)

print

(

"Index format:"

)

print

(

df_index

)

print

(

)

sample data: JSON column format (columns format)

json_columns

=

'''
{
    "name": ["Tom", "Jerry", "Mike"],
    "age": [28, 35, 42],
    "city": ["Beijing", "Shanghai", "Guangzhou"],
    "salary": [8000, 12000, 15000]
}
'''

with

open

(

'data_columns.json'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

json_columns

)

Read the JSON file (columns format)

df_columns

=

pd.

read_json

(

'data_columns.json'

,

orient

=

'columns'

)

print

(

"Columns format:"

)

print

(

df_columns

)

Expected output:



Records 格式:

    name  age       city  salary

0    Tom   28    Beijing    8000

1  Jerry   35   Shanghai   12000

2   Mike   42  Guangzhou   15000



Index 格式:

         age       city  salary

Tom       28    Beijing    8000

Jerry    35   Shanghai   12000

Mike     42  Guangzhou   15000



Columns 格式:

    name  age       city  salary

0    Tom   28    Beijing    8000

1  Jerry   参数          Shanghai   12000

2   Mike   42  Guangzhou   15000

Code analysis:

Example 2: read JSON from a string and a URL

read_json() Besides reading files, it also supports reading data from strings and URLs.

Example

import

pandas

as

pd

import

json

from

io

import

StringIO

Example 2a: Reading from a JSON string

json_string

=

'''
[
    {"product": "A", "sales": 100, "region": "North"},
    {"product": "B", "sales": 200, "region": "South"},
    {"product": "C", "sales": 150, "region": "East"}
]
'''

Use StringIO to turn a string into a file-like object

df_from_string

=

pd.

read_json

(

StringIO

(

json_string

)

)

print

(

"Read from string:"

)

print

(

df_from_string

)

print

(

)

You can also pass a JSON string directly as an argument

Note: Python strings must be escaped correctly

json_str_direct

=

'[{"product": "A", "sales": 100}, {"product": "B", "sales": 200}]'

df_direct

=

pd.

read_json

(

json_str_direct

)

print

(

"Pass string directly:"

)

print

(

df_direct

)

print

(

)

Example 2b: Reading JSON Lines format (one JSON object per line)

JSON Lines is a common log format

json_lines

=

'''{"name": "Tom", "score": 85}
{"name": "Jerry", "score": 92}
{"name": "Mike", "score": 78}
{"name": "Lucy", "score": 95}'''

with

open

(

'data_lines.json'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

json_lines

)

JSON Lines format must be read line by line

You can use the lines=True parameter (if JSONL format supports it)

Or handle it manually

df_list

=

[

]

with

open

(

'data_lines.json'

,

'r'

,

encoding

=

'utf-8'

)

as

f:

   

for

line

in

f:

        df_list.

append

(

json.

loads

(

line

)

)

df_lines

=

pd.

DataFrame

(

df_list

)

print

(

"Read JSON Lines format:"

)

print

(

df_lines

)

print

(

)

Example 2c: Reading from an API URL (requires network access)

A sample API is used here; replace it with a real URL in practice

df_api = pd.read_json('https://api.example.com/data')

print(df_api)

print

(

"Note: reading from a URL requires an actual network request"

)

Expected output:



Read from string:

  product  sales region

0       A    100   North

1       B    200   South

2       C    150    East



Pass string directly:

  product  sales

0       A    100

1       B    200



JSON Lines format reading:

    name  score

0    Tom     85

1  Jerry     92

2    Mike     78

3    Lucy     95



注意:从 URL 读取需要实际的网络请求

Code analysis:

Example 3: Handling dates and type conversion

Date and numeric types in JSON data need special handling.

Example

import

pandas

as

pd

Example 3a: Handling date fields

json_with_date

=

'''
[
    {"name": "Tom", "birthday": "1995-03-15", "join_date": "2020-01-10"},
    {"name": "Jerry", "birthday": "1988-07-22", "join_date": "2019-03-05"},
    {"name": "Mike", "birthday": "1981-11-30", "join_date": "2018-06-20"}
]
'''

with

open

(

'data_with_date.json'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

json_with_date

)

By default, date strings are read as object type

df_date

=

pd.

read_json

(

'data_with_date.json'

)

print

(

"Default read (date as string):"

)

print

(

df_date

)

print

(

"birthday type:"

,

df_date

[

'birthday'

]

.

dtype

)

print

(

)

Use convert_dates to automatically convert date columns

df_date_converted

=

pd.

read_json

(

'data_with_date.json'

,

convert_dates

=

[

'birthday'

,

'join_date'

]

)

print

(

"After date conversion:"

)

print

(

df_date_converted

)

print

(

"birthday type:"

,

df_date_converted

[

'birthday'

]

.

dtype

)

print

(

)

Example 3b: Specifying data types

json_mixed

=

'''
[
    {"id": "1", "name": "Tom", "score": 85.5},
    {"id": "2", "name": "Jerry", "score": 92.0},
    {"id": "3", "name": "Mike", "score": 78.5}
]
'''

with

open

(

'data_mixed.json'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

json_mixed

)

By default, id is read as an integer, name as a string, and score as a float

df_mixed

=

pd.

read_json

(

'data_mixed.json'

)

print

(

"Default type inference:"

)

print

(

df_mixed

)

print

(

"id type:"

,

df_mixed

[

'id'

]

.

dtype

)

print

(

)

Use dtype to explicitly specify types

df_typed

=

pd.

read_json

(

'data_mixed.json'

,

dtype

=

{

'id'

:

str

,

'score'

:

float

}

)

print

(

"After specifying types:"

)

print

(

df_typed

)

print

(

"id type:"

,

df_typed

[

'id'

]

.

dtype

)

Expected output:



默认读取(日期为字符串):

    name    birthday    join_date

0    Tom  1995-03-15  2020-01-10

1  Jerry  1988-07-22  2019-03-05

2    Mike  1981-11-30  2018-06-20



默认读取(日期为字符串):

    name    birthday    join_date

0    汤    Tom  1995-03-15  pandas 的 to_json() 和 read_json() 的完整配对示例

1  Jerry  1988-07-22  2019-03-05

2    Mike  1981-11-30  确保 JSON 数据格式一致

    1981-配对    to_json(orient='records')  配对    read_json(orient='records')

3   Mike  1981-11-30  to_json(orient='records')

...

    join_date    2018-06-20



birthday 类型: object



After date conversion:

birthday 类型: datetime64[ns]

Code analysis:


Notes


Summary

read_json() is the core function in pandas for reading JSON data and supports multiple JSON formats. As a common format for web APIs and data exchange, JSON is widely used in real-world data analysis.

Mastering the read_json() The key is to understand the different orient formats, as well as how dates and types are handled. Readers are encouraged to practice reading JSON data in different formats in real work.

Python math Module Common Pandas functions