How to Create a Dataframe From JSON in Python

To create a dataframe from JSON in Python, you can use the read_json() function from the pandas library.

The following example shows how to create a dataframe from JSON in Python using the read_json() function.

Using read_json() Function

We can use the read_json() function to read a JSON file into a dataframe.

Suppose we have the following JSON file named data.json:

[
    {"Date": "2023-01-03", "Product_Code": "A-101", "Product_Name": "Laptop", "Price": 4500, "Quantity": 1},
    {"Date": "2023-01-03", "Product_Code": "A-102", "Product_Name": "Mobile", "Price": 550, "Quantity": 2},
    {"Date": "2023-01-03", "Product_Code": "A-103", "Product_Name": "Printer", "Price": 250, "Quantity": 4},
    {"Date": "2023-01-03", "Product_Code": "B-101", "Product_Name": "Keyboard", "Price": 50, "Quantity": 0},
    {"Date": "2023-02-03", "Product_Code": "B-102", "Product_Name": "Scanner", "Price": 350, "Quantity": 3},
    {"Date": "2023-04-03", "Product_Code": "B-104", "Product_Name": "Mouse", "Price": 50, "Quantity": 1}
]

We can read this JSON file into a dataframe using the read_json() function:

# Import pandas library
import pandas as pd

# Read the JSON file into a Pandas dataframe
df = pd.read_json('data.json')

# Display the dataframe
print(df)

Output: 👇️

         Date Product_Code Product_Name  Price  Quantity
0  2023-01-03        A-101       Laptop   4500         1
1  2023-01-03        A-102       Mobile    550         2
2  2023-01-03        A-103      Printer    250         4
3  2023-01-03        B-101     Keyboard     50         0
4  2023-02-03        B-102      Scanner    350         3
5  2023-04-03        B-104        Mouse     50         1

In this example, we use the read_json() function to read the JSON file data.json into a dataframe df.

The output shows the dataframe created from the JSON file.

Conclusion

We can use the read_json() function from the pandas library to create a dataframe from a JSON file in Python.