Created
June 9, 2018 20:56
-
-
Save eliask/5e7b74e0113032f4d7407886b44b9a35 to your computer and use it in GitHub Desktop.
Convert newline-delimited JSON (ND-JSON) to CSV
This file contains hidden or 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 python3 | |
# Usage: ndjson_to_csv <files... or stdin> > output.csv | |
# NB: Assumes that each line is a simple JSON object with no nested arrays or objects | |
import csv | |
import json | |
import sys | |
import fileinput | |
from collections import namedtuple, OrderedDict | |
lines = fileinput.input() | |
writer = csv.writer(sys.stdout) | |
# Preserve field order for CSV header: | |
first = json.loads(next(lines), object_pairs_hook=OrderedDict) | |
header = list(first.keys()) | |
Row = namedtuple('Row', header) | |
writer.writerows([header, Row(**first)]) | |
for row in map(json.loads, lines): | |
writer.writerow(Row(**row)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment