How to put a Pandas DataFrame into a JSON file and read it again?


To put a Pandas DataFrame into a JSON file and read it again, we can use to_json() and read_json() methods.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
  • Print the input DataFrame, df.
  • Use to_json() method to dump the DataFrame into a JSON file.
  • Use read_json() method to read the JSON file.

Example

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)
print "Input DataFrame is:\n", df
print "JSON output for input DataFrame: ", df.to_json("test.json")

print "Reading the created JSON file"
print "Dataframe is: \n", pd.read_json("test.json")

Output

Input DataFrame is:
   x  y  z
0  5  4  9
1  2  7  3
2  7  5  5
3  0  1  1

JSON output for input DataFrame: None

Reading the created JSON file

Dataframe is:
   x  y  z
0  5  4  9
1  2  7  3
2  7  5  5
3  0  1  1

When we use df.to_json("test.json"), it creates a JSON file called "test.json" from the data given in the DataFrame.

Next, when we use pd.read_json("test.json"), it reads the data from test.json.

Updated on: 14-Sep-2021

832 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements