Skip to content

Instantly share code, notes, and snippets.

@keum
Last active December 23, 2015 07:59
Show Gist options
  • Save keum/6604459 to your computer and use it in GitHub Desktop.
Save keum/6604459 to your computer and use it in GitHub Desktop.
Python example on converting CSV into JSON format
This example came from Tom MacWright
Python standard library (plus simplejson for decimal encoding support) has all you need:
import csv, simplejson, decimal, codecs
data = open("in.csv")
reader = csv.DictReader(data, delimiter=",", quotechar='"')
with codecs.open("out.json", "w", encoding="utf-8") as out:
for r in reader:
for k, v in r.items():
# make sure nulls are generated
if not v:
r[k] = None
# parse and generate decimal arrays
elif k == "loc":
r[k] = [decimal.Decimal(n) for n in v.strip("[]").split(",")]
# generate a number
elif k == "geonameid":
r[k] = int(v)
out.write(simplejson.dumps(r, ensure_ascii=False, use_decimal=True)+"\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment