Getting values from JSON using Python


Question

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)

1
42
1/10/2019 4:45:37 PM

Accepted Answer

If you want to iterate over both keys and values of the dictionary, do this:

for key, value in data.items():
    print key, value
79
9/10/2012 2:04:09 PM

What error is it giving you?

If you do exactly this:

data = json.loads('{"lat":444, "lon":555}')

Then:

data['lat']

SHOULD NOT give you any error at all.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon