summaryrefslogtreecommitdiffstats
path: root/json2csv.py
blob: a9bcc81929249b9b4fe3f70a86213ee844e47a4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Read results in JSON format and output as CSV format.
#
# Aaron LI
# Created: 2016-04-27
# Updated: 2016-05-06
#

import sys
import json
import csv
import argparse
from collections import OrderedDict


def main():
    parser = argparse.ArgumentParser(
            description="Extract excess results from excess.json")
    parser.add_argument("json", help="input JSON file")
    parser.add_argument("csv", nargs="?", help="optional output CSV file")
    args = parser.parse_args()

    results = json.load(open(args.json), object_pairs_hook=OrderedDict)

    csv_writer = csv.writer(sys.stdout)
    csv_writer.writerow(results.keys())
    csv_writer.writerow(results.values())

    if args.csv:
        with open(args.csv, "w") as csv_file:
            csv_writer = csv.writer(csv_file)
            csv_writer.writerow(results.keys())
            csv_writer.writerow(results.values())


if __name__ == "__main__":
    main()