Skip to content

Instantly share code, notes, and snippets.

@msramalho
Created May 18, 2022 12:52
Show Gist options
  • Save msramalho/2bc8f48b1e23968ca128f2f4f6d1410a to your computer and use it in GitHub Desktop.
Save msramalho/2bc8f48b1e23968ca128f2f4f6d1410a to your computer and use it in GitHub Desktop.
Python script to convert a JSONfile with an array (or list of lines) into a CSV file
import json, csv, sys
#USAGE: python json_to_csv.py FILENAME.json
# filename to extract is 1st arg
# output file is appended with .csv
IN = sys.argv[1]
OUT = IN + ".csv"
# use this if the json is not an array, but rather one object per row
data = []
with open(IN) as inf:
for l in inf:
data.append(json.loads(l))
# use this if the json is an array already
# with open(IN) as inf:
# data = json.load(inf)
# get all unique fields
fields = set()
for d in data:
fields.update(d.keys())
# print some info before saving
print(f"got {len(data)} entries from {IN}")
print(data[0].keys())
with open(OUT, "w") as outf:
writer = csv.DictWriter(outf, fieldnames=fields)
writer.writeheader()
writer.writerows(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment