Getting values from JSON using Python

BrunoVillanova picture BrunoVillanova · Sep 10, 2012 · Viewed 381.2k times · Source

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)

Answer

Lior picture Lior · Sep 10, 2012

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

for key, value in data.items():
    print key, value