Last active
December 23, 2015 07:59
-
-
Save keum/6604459 to your computer and use it in GitHub Desktop.
Python example on converting CSV into JSON format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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