Skip to content

Instantly share code, notes, and snippets.

@yegeniy
Created January 18, 2013 16:56
Show Gist options
  • Save yegeniy/4566043 to your computer and use it in GitHub Desktop.
Save yegeniy/4566043 to your computer and use it in GitHub Desktop.
csv2json Copied from somewhere on the internet. Usage to get the json into an expanded format and into your clipboard: `python csv2json.py myfile.csv | python -m json.tool | pbcopy`
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 cells 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