Python How to Convert JSON to CSV with Example Code
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
How to Think About It
Algorithm
Code
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')
Dry Run
Let's trace converting JSON '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]' to CSV.
Load JSON
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
Write CSV header
header = ['name', 'age']
Write CSV rows
rows = [['Alice', 30], ['Bob', 25]]
| Step | Action | Value |
|---|---|---|
| 1 | Load JSON | [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}] |
| 2 | CSV Header | ['name', 'age'] |
| 3 | CSV 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
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')
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')
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| csv module with writer | O(n) | O(n) | Simple JSON lists, minimal dependencies |
| csv.DictWriter | O(n) | O(n) | Readable code, direct dict support |
| pandas DataFrame | O(n) | O(n) | Complex JSON, data analysis tasks |