Getting values from JSON using Python

469,265

Solution 1

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

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

Solution 2

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.

Solution 3

Using Python to extract a value from the provided Json

Working sample:-

import json
import sys

//load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

//dumps the json object into an element
json_str = json.dumps(data)

//load the json to a string
resp = json.loads(json_str)

//print the resp
print (resp)

//extract an element in the response
print (resp['test1'])

Solution 4

Using your code, this is how I would do it. I know an answer was chosen, just giving additional options.

data = json.loads('{"lat":444, "lon":555}')
    ret = ''
    for j in data:
        ret = ret+" "+data[j]
return ret

When you use "for" in this manner you get the key of the object, not the value, so you can get the value by using the key as an index.

Solution 5

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:

j = Json('{"lat":444, "lon":555}')
j.lat + ' ' + j.lon
Share:
469,265

Related videos on Youtube

BrunoVillanova
Author by

BrunoVillanova

Updated on August 15, 2021

Comments

  • BrunoVillanova
    BrunoVillanova almost 3 years

    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)

    • mgilson
      mgilson over 11 years
      Your first example works for me. What is the error it gives you?
    • mgilson
      mgilson over 11 years
      (unrelated), your second loop can be written as ' '.join(data)
    • BrunoVillanova
      BrunoVillanova over 11 years
      Using GAE with Python 2.7 and Bottle, it gives me "INFO 2012-09-10 13:54:58,583 dev_appserver.py:2967] "POST /app/939393/position HTTP/1.1" 500 -" on GAE Log console
    • Igor  Tischenko
      Igor Tischenko almost 5 years
      error traceback could be useful here, as the code in the first part is ok. it can't throw an error related to the question (for python 3.6 at least), error has to be in the import or function use (as return present)
  • Mohammad reza Golshahi
    Mohammad reza Golshahi about 2 years
    data.json()['test1'] !!!!