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")


  1. works beautifully--thanks!

  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,, using the import/export option in the manage worskpace button.

    Your help is welcome. Alejandro

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

  3. Where can I find the python module?

  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.

  5. In the event that there was viciousness in your marriage, you should seriously mull over getting a limiting request. A separation law office can enable you to step toward that archive, enabling you to feel protected at the earliest opportunity. divorce lawyer denver