wwl wwl - 1 year ago 94
JSON Question

dictionary from JSON to CSV

I have a JSON file containing a dictionary with many key-value pairs. I want to write it to a single CSV. One way to do this is simply to iterate through each key:

csvwriter.writerow([f["dict"]["key1"], f["dict"]["key2"],
f["dict"]["key3"], ... ])

This would be very tedious.

Another possibility is simply to use


but it writes everything into one column of the CSV file.

Is there a way I can write each value into one column of the CSV file?

Answer Source

You probably want to use a csv.DictWriter

The example in the official documentation is pretty straight-forward:

import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

Note that you must provide fieldnames to the constructor. If you're certain that all your dict have the same keys and don't care about the order of the output, you can just use list(first_dict) to get the column names, otherwise, you'll want to come up with a way to specify them more explicitly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download