使用Python从JSON获取值

2024-04-19 11:09:48 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图从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


Tags: 数据字符串injson元素fordatareturn
3条回答

使用Python从提供的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'])

如果要遍历字典的键和值,请执行以下操作:

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

它给了你什么错误?

如果你这样做:

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

然后:

data['lat']

根本不应该给您任何错误。

相关问题 更多 >