Skip to content

Instantly share code, notes, and snippets.

@maheshgawali
Last active February 23, 2019 07:41
Show Gist options
  • Save maheshgawali/9735189d6c36a02eb2d32e40c3784bfd to your computer and use it in GitHub Desktop.
Save maheshgawali/9735189d6c36a02eb2d32e40c3784bfd to your computer and use it in GitHub Desktop.
a simple python script for converting a csv to json, you can choose to use json, ujson or simplejson based on performance requirements
# inspired from http://www.andymboyle.com/2011/11/02/quick-csv-to-json-parser-in-python/
# refactored for using in python-3
# Also added ability to change json lib easily within json, ujson, simplejson
# reference for performance comparison json, ujson, simplejson - of https://medium.com/dataweave/json-vs-simplejson-vs-ujson-2887b2c128b2
import csv
import importlib
# you can use 'json', 'ujson' or 'simplejson'
json_lib_name = 'json'
json_lib = importlib.import_module(json_lib_name)
CSV_PATH = 'GIVE_YOUR_CSV_FILE_PATH_HERE.csv'
JSON_PATH = 'GIVE_YOUR_JSON_FILE_PATH_HERE.json'
# Do you want to pretty print the json ?
PRETTY_PRINT_JSON = True
JSON_INDENT = 4
f = open( CSV_PATH, 'r' )
# first row of csv is used as field names by DictReader
reader = csv.DictReader(f)
# Parse the CSV into JSON
if PRETTY_PRINT_JSON:
out = json_lib.dumps([ row for row in reader ], indent=JSON_INDENT)
else:
out = json_lib.dumps([ row for row in reader ])
print("JSON parsed!")
# Save the JSON
f = open( JSON_PATH, 'w')
f.write(out)
print('JSON saved to - "%s"' % JSON_PATH)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment