Skip to content

Instantly share code, notes, and snippets.

@drslump
Last active March 21, 2018 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drslump/fe0c45e5c955f2f689c8cc0afb6987ec to your computer and use it in GitHub Desktop.
Save drslump/fe0c45e5c955f2f689c8cc0afb6987ec to your computer and use it in GitHub Desktop.
json2csv & csv2json
#!/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))
#!/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