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:
![](https://static.packt-cdn.com/products/9781789343236/graphics/assets/3093bb79-a18a-40aa-9758-d5a8d340405b.png)
JSON 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:
![](https://static.packt-cdn.com/products/9781789343236/graphics/assets/a98a5f64-dc5b-44bd-8e85-be398a6fc207.png)
JSON output – column orientation
Orienting along the index acts like a transpose of the former case with a reversal of row and column...