Search code examples
pythongeojson

Append geoJSON feature with Python?


I have the following structure in a geojsonfile:

{"crs": 
  {"type": "name", 
   "properties": 
     {"name": "urn:ogc:def:crs:EPSG::4326"}
  }, 
   "type": "FeatureCollection", 
   "features": [
     {"geometry": 
       {"type": "Polygon", 
        "coordinates": [[[10.914622377957983, 45.682007076150505],
                         [10.927456267537572, 45.68179119797432], 
                         [10.927147329501077, 45.672795442796335],
                         [10.914315493899755, 45.67301125363092], 
                         [10.914622377957983, 45.682007076150505]]]},           
        "type": "Feature", 
        "id": 0, 
        "properties": {"cellId": 38}
   },
      {"geometry": 
        {"type": "Polygon", 
         "coordinates":
   ... etc. ...

I want to read this geoJSON into Google Maps and have each cell colored based on a property I calculated in Python for each cell individually. So my most question would be: How can I read the geoJSON in with Python and add another property to these Polygons (there are like 12 000 polygons, so adding them one by one is not an option), then write the new file?

I think what I'm looking for is a library for Python that can handle geoJSON, so I don't have to add these feature via srting manipulation.


Solution

  • The geoJSON is just a JSON doc (a simplification but is all you need for this purpose). Python reads that as a dict object.

    Since dict are updated inplace, we don't need to store a new variable for the geo objects.

    import json
    
    # read in json 
    geo_objects = json.load(open("/path/to/files"))
    
    # code ...
    
    for d in geo_objects:
        d["path"]["to"]["field"] = calculated_value
    
    json.dump(geofiles, open("/path/to/output/file"))
    

    No string manipulation needed, no need to load new library!