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?

1 Answer 1

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)
2
  • 1
    that one I tried too but when I try to import the file created like geojson.dump(stats, outfile) into QGIS I get the message that this is not a valid layer...
    – four-eyes
    Jun 11, 2016 at 21:24
  • look above in my answer
    – gene
    Jun 12, 2016 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.