124

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)

4
  • 4
    Your first example works for me. What is the error it gives you? Commented Sep 10, 2012 at 14:02
  • 1
    (unrelated), your second loop can be written as ' '.join(data) Commented Sep 10, 2012 at 14:04
  • 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 Commented Sep 10, 2012 at 14:07
  • 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) Commented Jul 11, 2019 at 8:36

6 Answers 6

144

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

for key, value in data.items():
    print(key, value)
Sign up to request clarification or add additional context in comments.

Comments

98

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.

Comments

24

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'])

4 Comments

data.json()['test1'] !!!!
@Sireesh Yarlagadda The code works if I put the JSON format inside the json.loads(...). But If I need to load the JSON file as a "myfile.json" with the related commands, it outputs an error.... What should I do??
Does anyone read my question?
import json file_path = 'data.json' with open(file_path, 'r') as file: data = json.load(file) print(data)
7

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.

1 Comment

iterating over keys and then getting the respective values from the dict is discouraged in python. use for key, value in data.items(): instead. It is more readable and less error-prone (also more efficient if one would care about that)
6

There's a Py library that has a module that facilitates access to Json-like dictionary key-values as attributes: pyxtension and Github source code

You can use it as:

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

Comments

0

With a JSON string such as '{"lat":444, "lon":555}', json.loads() creates a dictionary, so to get its values, you do so as you would get the values in a dictionary. Iteration over a dictionary is an iteration over its keys (for j in data: is the same as for j in data.keys():); however, to iterate over its values, you need to use .values():

import json
data = json.loads('{"lat":444, "lon":555}')
print(type(data))           # <class 'dict'>
print(data)                 # {'lat': 444, 'lon': 555}

for j in data.values():     # <--- iterate over values
    pass

Note that json.loads converts json arrays into lists. If you need to get a value of a dictionary in a list, then you will need to index the list for the dictionary first to get the value. This is an easy mistake to make especially if an API returns a JSON array with a single object in it. For example:

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

data['lat']                     # <--- TypeError
data[0]['lat']                  # <--- OK

If you want to get values from a JSON document, then open the file first and pass the file handle to json.load() instead. Depending on the document structure, json.load() would return dictionary or list, just like json.loads().

import json

with open('data.json', 'r') as f:
    data = json.load(f)

for j in data.values():
    pass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.