To convert JSON data to a CSV file in Python, you can use the json
and csv
libraries. Here’s a basic example of how you can do it:
import json
import csv
# Load JSON data from a file
with open('data.json', 'r') as json_file:
data = json.load(json_file)
# Specify the CSV file name
csv_file = 'data.csv'
# Open the CSV file in write mode
with open(csv_file, 'w', newline='') as csv_file:
# Create a CSV writer object
csv_writer = csv.writer(csv_file)
# Write the header row based on the keys in the JSON data
header = data[0].keys() if isinstance(data, list) and len(data) > 0 else data.keys()
csv_writer.writerow(header)
# Write the data rows
if isinstance(data, list):
for row in data:
csv_writer.writerow(row.values())
else:
csv_writer.writerow(data.values())
In this code:
- We import the
json
andcsv
libraries. - We load the JSON data from a file called
data.json
. - We specify the name of the CSV file (
data.csv
) where we want to write the CSV data. - We open the CSV file in write mode using the
csv.writer
object. - We write the header row based on the keys in the JSON data.
- We write the data rows by iterating over the JSON data and writing the values.
Make sure to replace 'data.json'
with the path to your JSON file and adjust the code as needed for your specific JSON structure.
If you have nested JSON data with complex structures, you may need to flatten the data or perform additional processing to handle it properly in the CSV file.