使用 Python 从 JSON 获取值

当我试图从 JSON 字符串中检索值时,它给了我一个错误:

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

但是,如果我对数据进行迭代,就会得到元素(latlon) ,而不是值:

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

返回: lat lon

我需要做什么才能得到 latlon的值? (444555)

539527 次浏览

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

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

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.

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.

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

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