Open In App

Convert JSON to CSV in Python

Last Updated : 08 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We can convert JSON to CSV in Python using the built-in json and csv modules.

What is JSON and CSV?

  • JSON is a lightweight, text-based data format commonly used to exchange data between web servers and clients. It stores data in key-value pairs and is typically used for data transmission in web applications.
  • CSV is a simple text-based file format used to store tabular data, where each line represents a row, and columns are separated by commas. It’s widely supported in data analysis tools like Excel, pandas, and other data processing software. 

Converting JSON to CSV

For simple JSON data consisting of key and value pairs, keys will be headers for the CSV file and values the descriptive data.

Example: Suppose the JSON file looks like this: 

python-json-to-csv

We want to convert the above JSON to CSV file with key as headers.

Python
import json
import csv

with open('data.json') as jf:
    d = json.load(jf)

Ed = d['emp_details']

df = open('data_file.csv', 'w')

cw = csv.writer(df)

c = 0

for emp in Ed:
    if c == 0:

        # Writing headers of CSV file
        h = emp.keys()
        cw.writerow(h)
        c += 1

    # Writing data of CSV file
    cw.writerow(emp.values())

df.close()

Output: 

python-json-to-csv-output

Explanation: This code reads a JSON file (data.json), extracts the emp_details list, and writes it into a CSV file (data_file.csv). It writes the headers (keys) from the first employee and then appends the employee details (values) as rows in the CSV. Finally, the file is closed.

And, if you are working on JSON data like the following:

[
    {‘Age’: 18.0, ‘Salary’: 20000.0, ‘Gender’: ‘Male’, ‘Country’: ‘Germany’, ‘Purchased’: ‘N’}
    {‘Age’: 19.0, ‘Salary’: 22000.0, ‘Gender’: ‘Female’, ‘Country’: ‘France’, ‘Purchased’: ‘N’}
    {‘Age’: 20.0, ‘Salary’: 24000.0, ‘Gender’: ‘Female’, ‘Country’: ‘England’, ‘Purchased’: ‘N’}
]

The below code will work perfectly for you (please format the code before running)

Python
import json
import csv

with open('G:\Akhil\jsonoutput.json') as jf:
    jd = json.load(jf)

df = open('G:\Akhil\jsonoutput.csv', 'w', newline='')
cw = csv.writer(df)

c = 0
for data in jd:
    if c == 0:
        header = data.keys()
        cw.writerow(header)
        c += 1
    cw.writerow(data.values())

df.close()

Output

Age,Salary,Gender,Country,Purchased
18.0,20000.0,Male,Germany,N
19.0,22000.0,Female,France,N
20.0,24000.0,Female,England,N

Explanation:

  • JSON file is read using the json.load() method, which loads the data into the variable jd.
  • The CSV file jsonoutput.csv is opened in write mode.
  • The code writes the header to the CSV file based on the keys of the first dictionary in jd. Then it writes the values of each dictionary as a row in the CSV file.

Related Articles:


Next Article

Similar Reads