Posted on Leave a comment

Python Script to Convert JSON to CSV

Here is an example Python script that converts a JSON file to a CSV file:

import json
import csv

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

# Open a CSV file for writing
with open('data.csv', 'w', newline='') as csv_file:
    # Create a CSV writer
    csv_writer = csv.writer(csv_file)
    
    # Write the headers
    csv_writer.writerow(json_data[0].keys())

    # Write the data
    for row in json_data:
        csv_writer.writerow(row.values())

This script assumes that the JSON file is an array of objects, where each object represents a row in the CSV file. It will write the keys of the first object to the headers of the csv file. It will then write the values of the each object to the csv file. It will use json library to load the json data and csv library to write the data to csv file You can customize this script to suit the specific format of your JSON data and the desired structure of your CSV file.

Leave a Reply

Your email address will not be published. Required fields are marked *