From b89564d7419df4c81416802496629e63ffb54b66 Mon Sep 17 00:00:00 2001 From: Aaron LI Date: Fri, 6 May 2016 20:02:40 +0800 Subject: json2csv.py: extract JSON results and output as CSV format --- extract_excess.py | 53 ----------------------------------------------------- json2csv.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 53 deletions(-) delete mode 100755 extract_excess.py create mode 100755 json2csv.py diff --git a/extract_excess.py b/extract_excess.py deleted file mode 100755 index 1983859..0000000 --- a/extract_excess.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# -# Extract the excess value and ratio results. -# -# Aaron LI -# Created: 2016-04-27 -# - -import sys -import os -import json -import csv -import argparse -from collections import OrderedDict - - -def extract_excess(data): - """ - Extract the excess value and ratio as well as other misc information - from the "data" dictionary. - """ - results = OrderedDict([ - ("name", data["name"]), - ("obsid", data["obsid"]), - ("model", data["model"]), - ("brightness_obs", data["brightness_obs"]), - ("brightness_model", data["brightness_model"]), - ("excess_value", data["excess_value"]), - ("excess_ratio", data["excess_ratio"]), - ]) - return results - - -def main(): - parser = argparse.ArgumentParser( - description="Extract excess results from excess.json") - parser.add_argument("excess_json", nargs="?", default="excess.json", - help="json file conatins excess results (default: excess.json)") - args = parser.parse_args() - - excess_data = json.load(open(args.excess_json)) - results = extract_excess(excess_data) - - # output results - csv_writer = csv.writer(sys.stdout) - csv_writer.writerow(results.keys()) - csv_writer.writerow(results.values()) - - -if __name__ == "__main__": - main() - diff --git a/json2csv.py b/json2csv.py new file mode 100755 index 0000000..a9bcc81 --- /dev/null +++ b/json2csv.py @@ -0,0 +1,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() -- cgit v1.2.2