While I am trying to retrieve values from JSON string, it gives me an error:
data = json.loads('{"lat":444, "lon":555}')
return data["lat"]
But, if I iterate over the data, it gives me the elements (lat
and lon
), but not the values:
data = json.loads('{"lat":444, "lon":555}')
ret = ''
for j in data:
ret = ret + ' ' + j
return ret
Which returns: lat lon
What do I need to do to get the values of lat
and lon
? (444
and 555
)
What error is it giving you?
If you do exactly this:
Then:
SHOULD NOT give you any error at all.
If you want to iterate over both keys and values of the dictionary, do this:
Using Python to extract a value from the provided Json
There's a Py library that has a module that facilitates access to Json-like dictionary key-values as attributes: https://github.com/asuiu/pyxtension You can use it as:
Using your code, this is how I would do it. I know an answer was chosen, just giving additional options.
When you use for in this manor you get the key of the object, not the value, so you can get the value, by using the key as an index.