convert json to csv in python

To convert JSON to CSV in Python, you can use the built-in json and csv modules. The json module allows you to load JSON data as a Python object, and the csv module lets you write Python objects to CSV files.

Here is some sample code that demonstrates how to convert a JSON file to CSV:

main.py
import json
import csv

# Read JSON file and load data as Python object
with open('input.json', 'r') as f:
    data = json.load(f)

# Open CSV file and write header row
with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(data[0].keys())

    # Write data rows
    for row in data:
        writer.writerow(row.values())
361 chars
16 lines

This code assumes that the JSON file contains an array of objects, where each object represents a single row in the CSV file. The first row of the CSV file will be a header row, containing the keys of the objects in the JSON array. Subsequent rows will contain the values of each object in the array.

Note that this code only works if the JSON file is well-formed and contains valid JSON data. If the JSON data is malformed, you will need to fix it before attempting to convert it to CSV.

gistlibby LogSnag