Search code examples
pythonjsongeojsonmin

Python - Using min() to find min value in JSON object?


So I have a geojson object that has:

"features" : [{"properties": {"rank": 10}},{"properties": {"rank": 2}}]

and so on. I want to find the minimum rank and use the min method. So I tried something like this:

features = geojson["features"]
min(features["properties"]["rank"])

and then:

features = geojosn["features"]["properties"]["rank"]
min(features)

and got this on both:

TypeError: List indices must be integers of slices, not str

What am I doing wrong? Any help would be greatly appreciated, thanks!!!


Solution

  • I'm assuming you have a list of features with properties (as @idjaw pointed out your data structure is invalid). Then geojson['features'] is a list and you aren't indexing the list. You can do this with a generator:

    min(feature["properties"]["rank"] for feature in geojson['features'])
    

    Alternatively if you want the whole feature back then you can use key:

    min(geojson['features'], key=lambda feature: feature["properties"]["rank"])