Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values from JSON using Python

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)

like image 705
BrunoVillanova Avatar asked Sep 10 '12 14:09

BrunoVillanova


People also ask

How do I extract data from a JSON file in Python?

So first thing you need to import the 'json' module into the file. Then create a simple json object string in python and assign it to a variable. Now we will use the loads() function from 'json' module to load the json data from the variable. We store the json data as a string in python with quotes notation.


2 Answers

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

for key, value in data.items():     print key, value 
like image 186
Lior Avatar answered Oct 06 '22 12:10

Lior


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.

like image 26
Pablo Santa Cruz Avatar answered Oct 06 '22 12:10

Pablo Santa Cruz