Shapefile into geojson conversion python 3

Srinuvas Bathula picture Srinuvas Bathula · Mar 30, 2017 · Viewed 14k times · Source
output_buffer = []
for features in range(0,layer.GetFeatureCount()):
    feat = layer.GetNextFeature()
    geom = feat.GetGeometryRef()
    result = feat.ExportToJson()
    output_buffer.append(result)

When I convert into geojson, I get output, but only one feature is getting formatted as JSON

I got output like this:

{"geometry": {"coordinates": [488081.726322771, 2360837.62927308], "type": "Point"}, "type": "Feature", "id": 0, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "BB_D2", "ExtendedEn": null, "SubClasses": null}}{"geometry": {"coordinates": [487523.119248441, 2361228.95273474], "type": "Point"}, "type": "Feature", "id": 1, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "Mil_D2", "ExtendedEn": null, "SubClasses": null}}..................

I would like to get output like this:

{"geometry": {"coordinates": [488081.726322771, 2360837.62927308], "type": "Point"}, "type": "Feature", "id": 0, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "BB_D2", "ExtendedEn": null, "SubClasses": null}}**,**    
{"geometry": {"coordinates": [487523.119248441, 2361228.95273474], "type": "Point"}, "type": "Feature", "id": 1, "properties": {"EntityHand": null, "Layer": "pipe", "Linetype": null, "Text": "Mil_D2", "ExtendedEn": null, "SubClasses": null}}**,**

Answer

alexisdevarennes picture alexisdevarennes · Nov 14, 2017

Please check out the following library: https://pypi.python.org/pypi/pyshp/1.1.7

import shapefile
from json import dumps

# 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
   
geojson = open("pyshp-demo.json", "w")
geojson.write(dumps({"type": "FeatureCollection", "features": buffer}, indent=2) + "\n")
geojson.close()

As noted in other answers, you could use geopandas:

import geopandas

shp_file = geopandas.read_file('myshpfile.shp')
shp_file.to_file('myshpfile.geojson', driver='GeoJSON')