Skip to content

Instantly share code, notes, and snippets.

@dvbportal
Created January 22, 2014 18:50
Show Gist options
  • Save dvbportal/8564846 to your computer and use it in GitHub Desktop.
Save dvbportal/8564846 to your computer and use it in GitHub Desktop.
CSV to JSON conversion (in Python)
import csv
import json
csvfile = open('DE.txt', 'r')
jsonfile = open('de.json', 'w')
fieldnames = ("countryCode","postalCode","placeName","adminName1","adminCode1","adminName2","adminCode2","adminName3","adminCode3","latitude","longitude","accuracy")
reader = csv.DictReader(csvfile, fieldnames, delimiter='\t')
jsonfile.write("{ \"docs\": [")
for row in reader:
lat = row["latitude"]
lon = row["longitude"]
row.pop("latitude")
row.pop("longitude")
row["loc"] = [float(lon), float(lat)]
json.dump(row, jsonfile)
jsonfile.write(",\n")
jsonfile.write("]}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment