Skip to content

Instantly share code, notes, and snippets.

@anjanesh
Last active April 28, 2019 04:21
Show Gist options
  • Save anjanesh/1835303 to your computer and use it in GitHub Desktop.
Save anjanesh/1835303 to your computer and use it in GitHub Desktop.
Convert CSV to JSON
import sys, csv, json
if len(sys.argv) == 1:
print "1 argument for filename required"
sys.exit()
gdoc = csv.reader(open(sys.argv[1]))
# Get the 1st line, assuming it contains the column titles
fieldnames = gdoc.next()
# Get the total number of columns
fieldnames_len = len(fieldnames)
data = [] # Empty list
i = 0
for row in gdoc:
# Add an empty dict to the list
data.append({})
for j in range(0, len(row)):
data[i][fieldnames[j]] = row[j]
# What if the last few columns are empty ? There may not be commas
for j in range(len(row), fieldnames_len):
data[i][fieldnames[j]] = ""
i = i + 1
print json.dumps(data)
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment