Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # i'm ashamed
- # it's shit, everything is shit
- import json
- from collections import OrderedDict
- def commaSeparateJSONData(json_list):
- csv_str = ''
- json_list_length = len(json_list)
- json_list_last_idx = json_list_length - 1
- for index in range(json_list_length):
- csv_str += '"{0}"'.format(str(json_list[index]).replace('\"', '\"\"'))
- if index < json_list_last_idx:
- csv_str += ','
- return csv_str + '\r\n'
- print("\nJSONS to CSV Converter")
- print("----------------------\n")
- while True:
- jsons_filename = input("Enter JSONS file (leave blank to exit): ").strip()
- if jsons_filename == '' :
- break
- try:
- jsons_fh = open(jsons_filename, 'rt')
- except IOError as err_inst:
- print("Error opening file {0}: {1}".format(jsons_filename, err_inst))
- continue
- else:
- csv_filename = jsons_fh.name + '.csv'
- print("Creating conversion file: {0}".format(csv_filename))
- try:
- csv_fh = open(csv_filename, 'wt', encoding='utf-8')
- csv_fh.truncate()
- except IOError as err_inst:
- print("Error writing file {0}: {1}".format(filename, err_inst))
- else:
- from json.decoder import JSONDecodeError
- try:
- lines_processed = 0
- line = jsons_fh.readline().strip()
- while line != '':
- json_obj = json.loads(line, object_pairs_hook=OrderedDict)
- if (csv_fh.tell() == 0):
- csv_fh.write(commaSeparateJSONData(list(json_obj.keys())))
- csv_fh.write(commaSeparateJSONData(list(json_obj.values())))
- lines_processed += 1
- line = jsons_fh.readline().strip()
- except JSONDecodeError as err_inst:
- print("JSON Error: {0}".format(err_inst))
- finally:
- csv_fh.close()
- finally:
- jsons_fh.close()
- print("Lines processed: ", lines_processed)
- print("Execution finished.")
- break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement