Pandas pd.read_json() function
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
- Return Type:
pd.DataFrameorpd.Series - By default a DataFrame is returned, which can be in two-dimensional tabular form.
- When
typ='series'returns a Series.
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'
)
(
"Records format:"
)
(
df_records
)
(
)
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'
)
(
"Index format:"
)
(
df_index
)
(
)
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'
)
(
"Columns format:"
)
(
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:
orient='records': JSON array format, where each row is a JSON object; this is the most commonly used format.orient='index': JSON object format, with keys used as the index.orient='columns': JSON column format, where keys are column names and values are arrays.- Correctly specifying the
orientparameter is essential for correctly parsing JSON data.
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
)
)
(
"Read from string:"
)
(
df_from_string
)
(
)
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
)
(
"Pass string directly:"
)
(
df_direct
)
(
)
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
)
(
"Read JSON Lines format:"
)
(
df_lines
)
(
)
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)
(
"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:
read_json()can accept a JSON string as input; useStringIOto turn the string into a file-like object.- JSON Lines format has one independent JSON object per line. It is commonly used in log processing and must be read line by line and then combined into a DataFrame.
- When reading from a URL, just pass the URL string directly, but network support is required.
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'
)
(
"Default read (date as string):"
)
(
df_date
)
(
"birthday type:"
,
df_date
[
'birthday'
]
.
dtype
)
(
)
Use convert_dates to automatically convert date columns
df_date_converted
=
pd.
read_json
(
'data_with_date.json'
,
convert_dates
=
[
'birthday'
,
'join_date'
]
)
(
"After date conversion:"
)
(
df_date_converted
)
(
"birthday type:"
,
df_date_converted
[
'birthday'
]
.
dtype
)
(
)
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'
)
(
"Default type inference:"
)
(
df_mixed
)
(
"id type:"
,
df_mixed
[
'id'
]
.
dtype
)
(
)
Use dtype to explicitly specify types
df_typed
=
pd.
read_json
(
'data_mixed.json'
,
dtype
=
{
'id'
:
str
,
'score'
:
float
}
)
(
"After specifying types:"
)
(
df_typed
)
(
"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:
convert_datesThe parameter specifies which columns need to be converted to date type.- By default,
convert_dates=TrueCommon date formats are recognized automatically. dtypeThe parameter lets you explicitly specify each column's data type to avoid type inference errors.
Notes
- Correctly specifying the
orientThe parameter is key to reading JSON data; different JSON structures require different orient values. - Dates in JSON are read as strings by default, so you need to use
convert_datesthe parameter to convert them to date type. - When reading a large JSON file, you can consider using
chunksizethe parameter to read in chunks. read_json()It supports reading from file paths, URLs, and JSON strings.- JSON Lines format must be parsed line by line and then combined into a DataFrame.
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.
Common Pandas functions