Advertisement
Guest User

JSONS to CSV

a guest
Oct 13th, 2016
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. # i'm ashamed
  2. # it's shit, everything is shit
  3.  
  4. import json
  5. from collections import OrderedDict
  6.  
  7. def commaSeparateJSONData(json_list):
  8.     csv_str = ''
  9.     json_list_length = len(json_list)
  10.     json_list_last_idx = json_list_length - 1
  11.    
  12.     for index in range(json_list_length):
  13.         csv_str += '"{0}"'.format(str(json_list[index]).replace('\"', '\"\"'))
  14.        
  15.         if index < json_list_last_idx:
  16.             csv_str += ','
  17.        
  18.     return csv_str + '\r\n'
  19.  
  20.  
  21. print("\nJSONS to CSV Converter")
  22. print("----------------------\n")
  23.  
  24. while True:
  25.     jsons_filename = input("Enter JSONS file (leave blank to exit): ").strip()
  26.     if jsons_filename == '' :
  27.         break
  28.    
  29.     try:
  30.         jsons_fh = open(jsons_filename, 'rt')
  31.     except IOError as err_inst:
  32.         print("Error opening file {0}: {1}".format(jsons_filename, err_inst))
  33.         continue
  34.     else:
  35.         csv_filename = jsons_fh.name + '.csv'
  36.         print("Creating conversion file: {0}".format(csv_filename))
  37.        
  38.         try:
  39.             csv_fh = open(csv_filename, 'wt', encoding='utf-8')
  40.             csv_fh.truncate()
  41.         except IOError as err_inst:
  42.             print("Error writing file {0}: {1}".format(filename, err_inst))
  43.         else:
  44.             from json.decoder import JSONDecodeError
  45.             try:
  46.                 lines_processed = 0
  47.                 line = jsons_fh.readline().strip()
  48.                 while line != '':
  49.                     json_obj = json.loads(line, object_pairs_hook=OrderedDict)
  50.                     if (csv_fh.tell() == 0):
  51.                         csv_fh.write(commaSeparateJSONData(list(json_obj.keys())))
  52.                    
  53.                     csv_fh.write(commaSeparateJSONData(list(json_obj.values())))
  54.                     lines_processed += 1
  55.                     line = jsons_fh.readline().strip()
  56.             except JSONDecodeError as err_inst:
  57.                 print("JSON Error: {0}".format(err_inst))
  58.             finally:
  59.                 csv_fh.close()
  60.        
  61.         finally:
  62.             jsons_fh.close()
  63.            
  64.             print("Lines processed: ", lines_processed)
  65.             print("Execution finished.")
  66.             break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement