0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert JSON to CSV with Example Code

Use Python's json module to load JSON data and csv module to write it to a CSV file, for example: import json, csv; data = json.load(open('file.json')); csv.writer(open('file.csv', 'w', newline='')).writerows([data[0].keys()] + [x.values() for x in data]).
📋

Examples

Input[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
Outputname,age Alice,30 Bob,25
Input[{"city": "NY", "temp": 20}, {"city": "LA", "temp": 25}]
Outputcity,temp NY,20 LA,25
Input[]
Output
🧠

How to Think About It

First, read the JSON data into Python as a list of dictionaries. Then, open a CSV file for writing. Write the dictionary keys as the CSV header row, and write each dictionary's values as a row in the CSV file.
📐

Algorithm

1
Load JSON data from a file or string into a list of dictionaries.
2
Open a new CSV file in write mode.
3
Extract the keys from the first dictionary to use as CSV headers.
4
Write the headers to the CSV file.
5
Iterate over each dictionary and write its values as a CSV row.
6
Close the CSV file.
💻

Code

python
import json
import csv

json_data = '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]'
data = json.loads(json_data)

with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(data[0].keys())
    for item in data:
        writer.writerow(item.values())

print('CSV file created as output.csv')
Output
CSV file created as output.csv
🔍

Dry Run

Let's trace converting JSON '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]' to CSV.

1

Load JSON

data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]

2

Write CSV header

header = ['name', 'age']

3

Write CSV rows

rows = [['Alice', 30], ['Bob', 25]]

StepActionValue
1Load JSON[{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
2CSV Header['name', 'age']
3CSV Rows['Alice', 30], ['Bob', 25]
💡

Why This Works

Step 1: Load JSON Data

Use json.loads() to convert JSON string into Python list of dictionaries.

Step 2: Write CSV Header

Extract keys from the first dictionary to write as CSV column headers using writer.writerow().

Step 3: Write CSV Rows

Write each dictionary's values as a row in the CSV file with writer.writerow().

🔄

Alternative Approaches

Using pandas library
python
import pandas as pd
import json

json_data = '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]'
data = json.loads(json_data)
df = pd.DataFrame(data)
df.to_csv('output.csv', index=False)
print('CSV file created with pandas')
Pandas simplifies conversion and handles complex JSON but adds dependency.
Using DictWriter from csv module
python
import json
import csv

json_data = '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]'
data = json.loads(json_data)

with open('output.csv', 'w', newline='') as csvfile:
    fieldnames = data[0].keys()
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(data)

print('CSV file created using DictWriter')
DictWriter writes dictionaries directly, improving readability and flexibility.

Complexity: O(n) time, O(n) space

Time Complexity

The code loops through each JSON object once to write CSV rows, so time grows linearly with data size.

Space Complexity

The entire JSON data is loaded into memory as a list of dictionaries, so space grows linearly with input size.

Which Approach is Fastest?

Using the csv module directly is fast and lightweight; pandas adds overhead but simplifies code for complex data.

ApproachTimeSpaceBest For
csv module with writerO(n)O(n)Simple JSON lists, minimal dependencies
csv.DictWriterO(n)O(n)Readable code, direct dict support
pandas DataFrameO(n)O(n)Complex JSON, data analysis tasks
💡
Always check if JSON data is a list of dictionaries before converting to CSV.
⚠️
Trying to write JSON directly to CSV without parsing it into dictionaries first.