Convert JSON to CSV Using Python

Jan 19, 2023

2 mins read

Published in

Python has in-build libraries which support JSON as well as CSV. Converting JSON to CSV in Python uses the built-in JSON modules. Here is an example of how you could use these modules to convert a JSON file to a CSV file:

JSON to CSV Python Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import csv
import json

# Open the JSON file
with open('data.json') as json_file:
    data = json.load(json_file)

# Create a new CSV file and write the data
with open('data.csv', 'w', newline='') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=data[0].keys())
    writer.writeheader()
    for row in data:
        writer.writerow(row)

In this example, the code first opens the JSON file using the open() function and the JSON module’s load() function, which reads the file’s contents and converts it to a Python object.

Then, it creates a new CSV file and uses the CSV module’s DictWriter() class to write the data to the file. The fieldnames for the writer are set to the keys of the first element of the data.

Please note that this code assumes that the JSON file is an array of objects, each having the same keys. If the JSON file has a different structure, you may need to adjust the code accordingly.

data.json

The data.json file in the previous example is a file that contains data in JSON format. It could be any file that has a valid JSON format, such as a file containing information about products, customers, or weather data. The file can be generated from different sources, such as an API or data scraping, or it could be a file that you have created on your own.

It is essential to mention that the structure of the JSON file should match the structure that is expected by the code. In the example I provided, the JSON file is an array of objects, with each object having the same keys. If the JSON file has a different structure, you may need to adjust the code accordingly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
  "employees": {
    "employee": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      },
      {
        "id": "2",
        "firstName": "Maria",
        "lastName": "Sharapova"
      },
      {
        "id": "3",
        "firstName": "James",
        "lastName": "Bond"
        
      }
    ]
  }
}

output as csv

id,firstName,lastName
1,Tom,Cruise
2,Maria,Sharapova
3,James,Bond

Sharing is caring!