Last active
March 21, 2018 20:14
-
-
Save drslump/fe0c45e5c955f2f689c8cc0afb6987ec to your computer and use it in GitHub Desktop.
json2csv & csv2json
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
#!/usr/bin/env python | |
# | |
# Converts a CSV (with column headers) to JSONL | |
# | |
import sys, csv, json | |
for row in csv.DictReader(sys.stdin): | |
print(json.dumps(row)) |
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
#!/usr/bin/env python | |
# | |
# Converts a JSONL (Json object per line) to CSV | |
# | |
# Note that columns will reflect the first JSON object processed. | |
# | |
import sys, csv, json | |
writer = None | |
for ln, row in enumerate(sys.stdin): | |
try: | |
data = json.loads(row) | |
except: | |
sys.stderr.write('Unable to parse JSON at line {}\n'.format(ln)) | |
if not writer: | |
writer = csv.DictWriter(sys.stdout, fieldnames=data.keys()) | |
writer.writeheader() | |
filtered = dict((k, data[k]) for k in data.keys() if k in writer.fieldnames) | |
writer.writerow(filtered) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment