summaryrefslogtreecommitdiffstats
path: root/json2csv.py
blob: 719319e1f2826c88b375525f341331d7924719a3 (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
#!/usr/bin/env python3
#
# 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="Read JSON results and output as CSV format")
    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()