Last active
July 27, 2024 19:48
-
-
Save andmerk93/ea7440f9aed8438bf2eba9858ffdedcf to your computer and use it in GitHub Desktop.
Little script to convert JSON to CSV
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
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