output_buffer = [] for features in range(0,layer.GetFeatureCount()): feat = layer.GetNextFeature() geom = feat.GetGeometryRef() result = feat.ExportToJson() output_buffer.append(result)Cuando convierto a geojson, obtengo resultados, pero solo una función se formatea como JSON
Obtuve una salida como esta:
{"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}}..................Me gustaría obtener una salida como esta:
{"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}}**,**Consulte la siguiente biblioteca: 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()Como se señaló en otras respuestas, podría usar geopandas:
import geopandas shp_file = geopandas.read_file('myshpfile.shp') shp_file.to_file('myshpfile.geojson', driver='GeoJSON')Para la conversión entre shapefile y geojson definitivamente usaría geopandas:
import geopandas myshpfile = geopandas.read_file('myshpfile.shp') myshpfile.to_file('myJson.geojson', driver='GeoJSON')Para agregar a @alexisdevarennes.
Ahora puede convertir a geojson usando PyShp en 1 o dos líneas:
import shapefile with shapefile.Reader("shapefile.shp") as shp: geojson_data = shp.__geo_interface__o
geojson_data = shapefile.Reader("shapefile.shp").__geo_interface__ejemplo de uso:
>>> geojson_data["type"] 'MultiPolygon'