Reading JSON
The read_json function reads JSON text into a DataFrame. JSON holds records as named fields inside curly brackets.
Read a small JSON list
This JSON text holds two records in square brackets. Each record holds a product and a units count.
import io
import pandas as pd
small_json = """[{"product": "Tea", "units": 2}, {"product": "Coffee", "units": 1}]"""
df = pd.read_json(io.StringIO(small_json))
print(df)JSON with prices
The same shape works for other fields. This text holds products and their prices.
import io
import pandas as pd
small_json = """[{"product": "Mug", "price": 12.00}, {"product": "Lamp", "price": 24.00}]"""
df = pd.read_json(io.StringIO(small_json))
print(df)Example
import io
import pandas as pd
ORDERS_JSON = """[{"order_id": 101, "product": "Tea", "units": 2}, {"order_id": 102, "product": "Coffee", "units": 1}, {"order_id": 103, "product": "Mug", "units": 3}]"""
orders = pd.read_json(io.StringIO(ORDERS_JSON))
print(orders)Key points
- Use pd.read_json to read JSON text.
- Use io.StringIO to turn JSON text into something read_json can read.
- Each JSON record becomes one row of the DataFrame.
- Each field name becomes a column name.
- Print the orders to see all three rows.
In this example, three orders sit in a text variable named ORDERS_JSON. The io.StringIO call turns that text into something read_json can read. The read_json call turns it into a DataFrame named orders. The print shows all three rows.
Note
JSON is a common shape for data sent between programs.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which function reads JSON text into a DataFrame?