Advertisement
metalx1000

CSV to JSON converter python

Aug 3rd, 2018
2,773
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import sys, getopt
  3. import csv
  4. import json
  5.  
  6. #usage
  7. if ((len(sys.argv) < 3)):
  8.     print """\
  9.        USAGE: csv2json -i users.csv -o users.json -f pretty
  10.    """
  11.     sys.exit(1)
  12. #Get Command Line Arguments
  13. def main(argv):
  14.     input_file = ''
  15.     output_file = ''
  16.     format = ''
  17.     try:
  18.         opts, args = getopt.getopt(argv,"hi:o:f:",["ifile=","ofile=","format="])
  19.     except getopt.GetoptError:
  20.         print 'csv_json.py -i <path to inputfile> -o <path to outputfile> -f <dump/pretty>'
  21.         sys.exit(2)
  22.     for opt, arg in opts:
  23.         if opt == '-h':
  24.             print 'csv_json.py -i <path to inputfile> -o <path to outputfile> -f <dump/pretty>'
  25.             sys.exit()
  26.         elif opt in ("-i", "--ifile"):
  27.             input_file = arg
  28.         elif opt in ("-o", "--ofile"):
  29.             output_file = arg
  30.         elif opt in ("-f", "--format"):
  31.             format = arg
  32.     read_csv(input_file, output_file, format)
  33.  
  34. #Read CSV File
  35. def read_csv(file, json_file, format):
  36.     csv_rows = []
  37.     with open(file) as csvfile:
  38.         reader = csv.DictReader(csvfile)
  39.         title = reader.fieldnames
  40.         for row in reader:
  41.             csv_rows.extend([{title[i]:row[title[i]] for i in range(len(title))}])
  42.         write_json(csv_rows, json_file, format)
  43.  
  44. #Convert csv data into json and write it
  45. def write_json(data, json_file, format):
  46.     with open(json_file, "w") as f:
  47.         if format == "pretty":
  48.             f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False))
  49.         else:
  50.             f.write(json.dumps(data))
  51.  
  52. if __name__ == "__main__":
  53.    main(sys.argv[1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement