Skip to content

Instantly share code, notes, and snippets.

@andmerk93
Last active July 27, 2024 19:48
Show Gist options
  • Save andmerk93/ea7440f9aed8438bf2eba9858ffdedcf to your computer and use it in GitHub Desktop.
Save andmerk93/ea7440f9aed8438bf2eba9858ffdedcf to your computer and use it in GitHub Desktop.
Little script to convert JSON to CSV
from sys import argv
from json import load
from csv import DictWriter
from os.path import exists
filename = 'json.json'
if len(argv) > 1:
filename = argv[1]
with open(filename, 'r', encoding='utf-8') as file:
json_objs = load(file)
filename_csv = filename.split('.')[0] + '.csv'
write_headers = not exists(filename_csv)
headers = []
for obj in json_objs:
headers.extend(obj.keys())
headers = sorted(set(headers))
with open(filename_csv, 'a+', encoding='utf-8', newline='') as file:
writer = DictWriter(file, fieldnames=headers)
if write_headers:
writer.writeheader()
writer.writerows(json_objs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment