diff options
author | Aaron LI <aaronly.me@gmail.com> | 2016-03-31 10:57:34 +0800 |
---|---|---|
committer | Aaron LI <aaronly.me@gmail.com> | 2016-03-31 10:57:34 +0800 |
commit | c9c896dea2ba43551c4e10bd49666105449e9bd7 (patch) | |
tree | e94b73f17b2d776c2acd4c9549657f500c3dc7ce /cli/csv2json.py | |
parent | 2b6cb9b655a53d43b32a8a211287c82f4f59999a (diff) | |
download | atoolbox-c9c896dea2ba43551c4e10bd49666105449e9bd7.tar.bz2 |
add all scripts/tools
Diffstat (limited to 'cli/csv2json.py')
-rwxr-xr-x | cli/csv2json.py | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/cli/csv2json.py b/cli/csv2json.py new file mode 100755 index 0000000..54f6be2 --- /dev/null +++ b/cli/csv2json.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# This is a simple tool that converts CSV file into a JSON file. +# The first line of the input CSV file is used as the field names. +# +# Use 'OrderedDict' to keep the input fields order. +# +# Aaron LI +# 2015/06/11 +# + +from __future__ import print_function, division + +__version__ = "0.1.0" +__date__ = "2015/06/11" + +import sys +import argparse +import csv +import json + +from collections import OrderedDict + + +def csv2json(csvfile, jsonfile=None): + """ + Convert CSV data to JSON data. + The first line of CSV data is used as the field names. + + Return: + If jsonfile is None, then return a list of JSON dict. + """ + if not hasattr(csvfile, "read"): + csvfile = open(csvfile, "r") + if (jsonfile is not None) and (not hasattr(jsonfile, "write")): + jsonfile = open(jsonfile, "w") + csvdata = list(csv.reader(csvfile)) + fieldnames = csvdata[0] + # use 'OrderedDict' to keep fields order + jsondata = [ OrderedDict(zip(fieldnames, row)) for row in csvdata[1:] ] + csvfile.close() + if jsonfile is None: + return jsondata + else: + # 'ensure_ascii=False' to support UTF-8 + json.dump(jsondata, jsonfile, ensure_ascii=False, indent=4) + jsonfile.close() + + +def main(): + # command line options & arguments + parser = argparse.ArgumentParser( + description="Simple CSV to JSON convertor") + parser.add_argument("-V", "--version", action="version", + version="%(prog)s " + "%s (%s)" % (__version__, __date__)) + parser.add_argument("csvfile", help="Input CSV file") + parser.add_argument("jsonfile", nargs="?", default=sys.stdout, + help="Output JSON file (default stdout)") + args = parser.parse_args() + + csv2json(args.csvfile, args.jsonfile) + + +if __name__ == "__main__": + main() + |