Stophface Stophface - 7 months ago 27
Python Question

Iterating over geoJSON

My geoJSON looks like so

{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},

"features": [{
"type": "Feature",
"properties": {
"value1": "abc",
"value2": 0,
"value3": 0.99,
"value4": "def",
"value5": "882.3",
"value6": 12,
},
"geometry": {
"type": "Point",
"coordinates": [1, 1]
}
}
]
}


I want to access
properties
and check some
values
for a
key


for features in geoJsonPoints["features"]:
for interesting in features["properties"]["value1"]:
print interesting
print "!"


I get


a

!

b

!

c

!


Why is that?! It seems like my loop does not return me a dictionary?!

If I do this

for features in geoJsonPoints["features"]:
for interesting in features["properties"]:
print type(intereseting)
print interesting


I get


type 'unicode'

value1

type 'unicode'

value2

...


Why isnt that a dictionary? And, if its not a dictionary, why can I access the values behind the "unicode" like in the first loop I showed?!

Answer

features["properties"]["value1"] points to abc string which you iterate over character by character. Instead, you probably meant to iterate over the properties dictionary:

for property_name, property_value in features["properties"].items():
    print(property_name, property_value)

Or, you can loop over the dictionary keys:

for property_name in features["properties"]:
    print(property_name, features["properties"][property_name])

See more about dictionaries and looping techniques here: