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

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

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:

[{"name":"AA","age":34},{"name":"BB","age":12},{"name":"CC","age":56},{"name":"DD","age":43},{"name":"EE","age":23},{"name":"HH","age":41},{"name":"II","age":52}]


...