Files

64 lines
2.7 KiB
Python
Executable File

#!/usr/bin/env python3
# json2csv — convert a flat JSON array to CSV, flattening nested objects with dot-notation keys.
# Usage: json2csv [--flatten] input.json [output.csv]
"""json2csv: JSON array to CSV. Nested objects are flattened to dotted column
names (`address.city`), lists become JSON strings, and the column set is the
union of all keys — so ragged JSON still produces one clean table."""
import argparse, csv, json, sys
def flatten(obj, prefix=""):
out = {}
if isinstance(obj, dict):
for k, v in obj.items():
out.update(flatten(v, f"{prefix}{k}." if prefix else f"{k}."))
elif isinstance(obj, list):
out[prefix.rstrip(".")] = json.dumps(obj)
else:
out[prefix.rstrip(".")] = obj
return out
def convert(inp, out, do_flatten=True):
with open(inp, encoding="utf-8") as f: data = json.load(f)
if isinstance(data, dict): data = [data]
if not isinstance(data, list): raise SystemExit("json2csv: top level must be a JSON array (or single object)")
rows = [flatten(r) if do_flatten else r for r in data]
cols = []
for r in rows:
for k in r:
if k not in cols: cols.append(k)
fh = open(out, "w", newline="", encoding="utf-8") if out else sys.stdout
try:
w = csv.DictWriter(fh, fieldnames=cols)
w.writeheader()
for r in rows: w.writerow({k: ("" if r.get(k) is None else r.get(k)) for k in cols})
finally:
if out: fh.close()
print(f"json2csv: {len(rows)} rows, {len(cols)} columns -> {out or 'stdout'}", file=sys.stderr)
return 0
def selftest():
import tempfile, os, csv as _csv
with tempfile.TemporaryDirectory() as d:
j = os.path.join(d, "a.json")
json.dump([{"name": "ann", "addr": {"city": "Oslo", "zip": "0150"}, "tags": ["x", "y"]},
{"name": "bob", "addr": {"city": "Bergen"}}], open(j, "w"))
o = os.path.join(d, "a.csv")
assert convert(j, o) == 0
rows = list(_csv.DictReader(open(o)))
assert rows[0]["addr.city"] == "Oslo" and rows[0]["tags"] == '["x", "y"]', rows
assert rows[1]["addr.zip"] == ""
print("json2csv selftest: PASS"); return 0
def main():
ap = argparse.ArgumentParser(description="Convert a flat JSON array to CSV, flattening nested objects to dotted keys.")
ap.add_argument("input", nargs="?"); ap.add_argument("output", nargs="?")
ap.add_argument("--no-flatten", action="store_true", help="leave nested objects as JSON strings in one column")
ap.add_argument("--selftest", action="store_true")
a = ap.parse_args()
if a.selftest: return selftest()
if not a.input: ap.error("need an input JSON file")
return convert(a.input, a.output, not a.no_flatten)
if __name__ == "__main__":
sys.exit(main())