Write a Python code to read JSON data from a file and convert it to dataframe, CSV files


Assume you have the following sample json data stored in a file as pandas_sample.json

{
   "employee": {
      "name": "emp1",
      "salary": 50000,
      "age": 31
   }
}

The result for after converting to csv as,

,employee
age,31
name,emp1
salary,50000

Solution

To solve this, we will follow the steps given below −

  • Create pandas_sample.json file and store the JSON data.

  • Read json data from the file and store it as data.

data = pd.read_json('pandas_sample.json')
  • Convert the data into dataframe

df = pd.DataFrame(data)
  • Apple df.to_csv function to convert the data as csv file format,

df.to_csv('pandas_json.csv')

Example

Let’s see the below implementation to get a better understanding −

import pandas as pd
data = pd.read_json('pandas_sample.json')
df = pd.DataFrame(data)
df.to_csv('pandas_json.csv')

Output

employee
age 31
name emp1
salary 50000

Updated on: 24-Feb-2021

861 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements