Created
February 26, 2021 03:21
-
-
Save thisismattmiller/96022ed1bf55e22b1ce6141d93cbc399 to your computer and use it in GitHub Desktop.
jsontocsv.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import csv | |
import glob | |
# we need to know the headers, not all files may have all headers so make a big list first | |
headers = [] | |
for filename in glob.glob("exhibitions/*.json"): | |
with open(filename, "r") as data: | |
json_file = json.load(data) | |
for key in json_file.keys(): | |
if key not in headers: | |
headers.append(key) | |
print(headers) | |
# make a new writer, using DictWriter | |
with open('output.csv','w') as outfile: | |
# pass the headers we know about | |
writer = csv.DictWriter(outfile, fieldnames=headers) | |
writer.writeheader() | |
# loop through the files again | |
for filename in glob.glob("exhibitions/*.json"): | |
with open(filename, "r") as data: | |
json_file = json.load(data) | |
writer.writerow(json_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment