|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import sys, json, csv, string |
| 3 | + |
| 4 | +if len(sys.argv) != 3: |
| 5 | + sys.exit("usage: json2csv.py input.json output.csv") |
| 6 | + |
| 7 | +try: |
| 8 | + data = json.load(open(sys.argv[1])) |
| 9 | +except Exception: |
| 10 | + sys.exit("invalid json") |
| 11 | + |
| 12 | +if set(data) != {"CORE", "LB", "PAR"}: |
| 13 | + sys.exit("invalid categories") |
| 14 | + |
| 15 | +arches = [] |
| 16 | +seen = set() |
| 17 | +for cat in data.values(): |
| 18 | + if not isinstance(cat, dict): |
| 19 | + sys.exit("data not 2-dimensional") |
| 20 | + for param in cat.values(): |
| 21 | + if not isinstance(param, dict): |
| 22 | + sys.exit("data not 2-dimensional") |
| 23 | + for a in param.keys(): |
| 24 | + if a not in seen: |
| 25 | + seen.add(a) |
| 26 | + arches.append(a) |
| 27 | + |
| 28 | +cols = 1 + len(arches) |
| 29 | +empty = [""] * cols |
| 30 | + |
| 31 | +with open(sys.argv[2], "w", newline="") as f: |
| 32 | + w = csv.writer(f, lineterminator="\n") |
| 33 | + w.writerow(["Architecture", *arches]) |
| 34 | + w.writerow(empty) |
| 35 | + cats = list(data.items()) |
| 36 | + for ci, (cname, cat) in enumerate(cats): |
| 37 | + w.writerow([f"{cname}:"] + [""] * (cols - 1)) |
| 38 | + for pname, param in cat.items(): |
| 39 | + row = [pname] |
| 40 | + for a in arches: |
| 41 | + v = param.get(a, "") |
| 42 | + if isinstance(v, list): |
| 43 | + row.append(json.dumps(v)) |
| 44 | + elif isinstance(v, str) and not v == "": |
| 45 | + row.append('"' + v + '"') |
| 46 | + else: |
| 47 | + row.append(v) |
| 48 | + w.writerow(row) |
| 49 | + if ci != len(cats) - 1: |
| 50 | + w.writerow(empty) |
0 commit comments