2

How would I write a proper geoJson, readable by a GIS, from the results of the rasterstats package?

stats = zonal_stats("somePolygons.shp",
                     "someTif.tif",
                    geojson_out=True)

Something like

import geojson
with open("newfile.geojson", "w") as myFile:
     myfile.write(geojson.dump(stats))

does not work. The object I am getting from rasterstats is a geoJson. There are 200 Polygons in my geoJson object. Do I really have to write my geoJson "manually" like suggested in an answere here, or is there a way to do that automatically?

four-eyes
  • 3,378
  • 5
  • 33
  • 58

1 Answers1

2

It is a basic Python json problem (How do I write JSON data to a file in Python?)

 from rasterstats import zonal_stats
 stats = zonal_stats("a_poly.shp", "test.tif",geojson_out=True))
 # as the result is a json/geojson object
 import json # or geojson
 with open('newfile.geojson', 'w') as outfile:
      json.dump(stats, outfile) # or geojson.dump(stats, outfile)

Look also at Writing result of PyQGIS to shapefile

New

If is is for a GIS, you need a type Feature or FeatureCollection (dictionary with key Feature or FeatureCollection)

from rasterstats import zonal_stats
stats = zonal_stats("a_poly.shp", "test.tif",geojson_out=True))
result = {"type": "FeatureCollection","features": stats}
import json # or geojson
with open('newfile.geojson', 'w') as outfile:
   json.dump(result, outfile) # or geojson.dump(result, outfile)
gene
  • 54,868
  • 3
  • 110
  • 187