Pages

Tuesday, July 23, 2013

Shapefile to GeoJSON

Here's a quick example by Martin Laloux using the new PyShp geo-interface and the built-in json module to convert a shapefile to geojson in pure Python:
 import shapefile
   # read the shapefile
   reader = shapefile.Reader("my.shp")
   fields = reader.fields[1:]
   field_names = [field[0] for field in fields]
   buffer = []
   for sr in reader.shapeRecords():
       atr = dict(zip(field_names, sr.record))
       geom = sr.shape.__geo_interface__
       buffer.append(dict(type="Feature", \
        geometry=geom, properties=atr)) 
   
   # write the GeoJSON file
   from json import dumps
   geojson = open("pyshp-demo.json", "w")
   geojson.write(dumps({"type": "FeatureCollection",\
    "features": buffer}, indent=2) + "\n")
   geojson.close()

5 comments:

  1. works beautifully--thanks!

    ReplyDelete
  2. Hi,

    I wonder if you can support me to upload the following JSON code created based on your python lines. I need to upload it for my workspace in google engine, https://earthengine.google.org/#workspace, using the import/export option in the manage worskpace button.

    Your help is welcome. Alejandro

    {
    "type": "FeatureCollection",
    "features": [
    {
    "geometry": {
    "type": "Point",
    "coordinates": [
    -77.58671228784164,
    0.7965033408566455
    ]
    },
    "type": "Feature",
    "properties": {
    "tile": "h10v08",
    "id_join": "079Nr",
    "region": "narino",
    "OBJECTID_1": 1
    }
    }
    ]
    }

    ReplyDelete
  3. Where can I find the python module?

    ReplyDelete
  4. Hello! Thanks for this code. I have little problem that I have hundreds of shape file in different name and i want to convert into geojson and want to keep the same name for geojson file. I am trying using glob.glob but it is not working. any help? I am new in this! Thanks in advance.

    ReplyDelete