The to_json() function allows any DataFrame object to be converted into a JSON string or written to a JSON file if the file path is specified:
df = pd.DataFrame({"Col1": [1, 2, 3, 4, 5], "Col2": ["A", "B", "B", "A", "C"], "Col3": [True, False, False, True, True]})
df.to_json()
Take a look at the following output:
The orientation of the data in the JSON can be altered. The to_json() function has an orient argument which can be set for the following modes: columns, index, record, value, and split. Columns is the default setting for orientation:
df.to_json(orient="columns")
Take a look at the following output:
Orienting along the index acts like a transpose of the former case with a reversal of row and column indices in the JSON dictionary:
df.to_json(orient="index")
Take a look at the following output:
Setting orient as records creates a JSON structure where each record or row from the original DataFrame retains its structural form:
df.to_json(orient="records")
Take a look at the following output:
When the orient option is set to values, both row indices and column indices vanish from the picture:
df.to_json(orient="values")
Take a look at the following output:
The split orientation defines a JSON made up of entities such as column, index, and data:
df.to_json(orient="split")
Take a look at the following output:
Setting orient to table brings out aspects such as schema and field:
df.to_json(orient="table")
Take a look at the following output:
The date_format argument of to_json() allows timestamps in the DataFrame to be converted into either epoch format or iso format.
An unsupported datatype such as complex can be handled by specifying the type conversion to be followed through the default_handler argument.