How to Write a DataFrame to JSON in Pandas

01.08.2021

Intro

In a previous article, we learned how to read json using pandas. Pandas also provides us with a way to write json data. In this article, we will learn how to write json files using pandas.

Writing Json into a DataFrame

To write json, we can pass a file name to the write_json method. In our example, we will read a local file into a dataframe. Pandas will convert our dataframe to a json file.

import pandas as pd
import json   


df = pd.DataFrame([
	{
		"person": "James",
		"sales": 1000,
	},
	{
		"person": "Clara",
		"sales": 3000,
	}
])

df = pd.to_json('./data.json')

print(df.head())