Skip to content

Instantly share code, notes, and snippets.

@avdata99
Created June 22, 2017 20:29
Show Gist options
  • Save avdata99/239e3743dfe06ddb3f6d61710578b5fa to your computer and use it in GitHub Desktop.
Save avdata99/239e3743dfe06ddb3f6d61710578b5fa to your computer and use it in GitHub Desktop.
Transform an ugly CSV with GeoJSON field to real and valid GeoJSON (optionally to KML with ogr2ogr)
# Convertir CSV con un campo GeoJson en GeoJson de verdad
""" Muestra de los datos
barrio_nombre,localidad_comuna_nombre,partido_departamento_nombre,provincia_nombre,geometry
Sakura,Burzaco,Almirante Brown,Buenos Aires,"{""type"":""MultiPolygon"",""coordinates"":[[[[-58.3932940197438,-34.8414643460426],[-58.3897210142988,-34.8411327603842],[-58.3895424606404,-34.8422852562742],[-58.3931483187865,-34.8425747694022],[-58.3932940197438,-34.8414643460426]]]]}"
Barrio Tharram I,Burzaco,Almirante Brown,Buenos Aires,"{""type"":""MultiPolygon"",""coordinates"":[[[[-58.4011976024542,-34.8158546691101],[-58.4042565185486,-34.8173238122425],[-58.4058282782524,-34.8152186171327],[-58.4027190430739,-34.8137432573857],[-58.4011976024542,-34.8158546691101]]]]}"
Barrio Tharram II,Burzaco,Almirante Brown,Buenos Aires,"{""type"":""MultiPolygon"",""coordinates"":[[[[-58.4072933057172,-34.8191618268144],[-58.4090854427554,-34.8166801468689],[-58.407535685131,-34.8159373702445],[-58.4074343864498,-34.8160800560938],[-58.4058081212686,-34.8152779373624],[-58.4041142459366,-34.8175469981266],[-58.4072933057172,-34.8191618268144]]]]}"
"""
import csv
import json
import sys
path = 'barriospopulares.csv'
fieldnames = ['barrio_nombre','localidad_comuna_nombre','partido_departamento_nombre','provincia_nombre','geometry']
geojson_final = {"type": "FeatureCollection", "features": []}
with open(path) as csvfile:
reader = csv.DictReader(csvfile, fieldnames=fieldnames,
delimiter=',',
quotechar='"')
header = reader.__next__()
for row in reader:
geojson_base = row['geometry'].strip()
geojson = json.loads(geojson_base)
g = {"type": "Feature", "geometry": geojson, "properties": {} }
# agregar los otros campos como propiedades del geojson
for field in row.keys():
# no agregar de nuevo el mismo!
if field != 'geometry':
g['properties'][field] = row[field]
geojson_final['features'].append(g)
with open('barriospopulares.geojson', 'w') as outfile:
res = json.dumps(geojson_final, indent=4)
outfile.write(res)
outfile.close()
# PASAR A KML si fuera necesario
# ogr2ogr -f KML barrios.kml barrios.geojson
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment