How to Create Array of JSON From Dataframe in Python

To create an array of JSON from a dataframe in Python, you can use the to_json() function.

The following example shows how to create an array of JSON from a dataframe in Python using the to_json() function.

Using to_json() Function

We can use the to_json() function to create an array of JSON from a dataframe.

Suppose we have the following dataframe:

# Import libraries
import pandas as pd
import json

# Create the DataFrame
data = {'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
        'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
        'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
        'Price': [4500, 550, 250, 50, 350, 50],
        'Status': [1, 1, 1, 0, 1, 1]}

# Create dataframe        
office_stuff = pd.DataFrame(data)

# Convert the "office_stuff" DataFrame to an array of JSON objects
json_data = json.loads(office_stuff.to_json(orient='records'))

# Print the array of JSON objects
print(json_data)

Output: 👇️

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

In this example, we use the to_json() function to convert the dataframe office_stuff to an array of JSON objects json_data. The output shows the array of JSON objects created from the dataframe.

Conclusion

We can use the to_json() function to create an array of JSON from a dataframe in Python.