+2 votes
ago in Programming Languages by (20.2k points)
I want to save the data of a pandas dataframe to a JSON file. Which function should I use for it?

1 Answer

0 votes
ago by (35.8k points)

pandas to_json() function can be used to convert a DataFrame to a JSON string. The format of the JSON string is set using the parameter 'orient'. The set of possible orients is:

'split' : dict like {index -> [index], columns -> [columns], data -> [values]}
'records' : list like [{column -> value}, ... , {column -> value}]
'index' : dict like {index -> {column -> value}}
'columns' : dict like {column -> {index -> value}}
'values' : just the values array

Here is an example to create a JSON file using to_json() function with orient="records":

import pandas as pd
df = pd.DataFrame({"name": ['AA', 'BB', 'CC', 'DD', 'EE', 'HH', 'II'], "age": [34, 12, 56, 43, 23, 41, 52]})
filename = "testfile.json"
df.to_json(filename, orient='records')

The above code will create the file "testfile.json" with the following record: