Created
May 18, 2022 12:52
-
-
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
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, 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