Bru*_*ova 47 python json simplejson
当我尝试从JSON字符串中检索值时,它会给我一个错误:
data = json.loads('{"lat":444, "lon":555}')
return data["lat"]
Run Code Online (Sandbox Code Playgroud)
但是,如果我迭代数据,它会给我元素(lat
和lon
),但不是值:
data = json.loads('{"lat":444, "lon":555}')
ret = ''
for j in data:
ret = ret + ' ' + j
return ret
Run Code Online (Sandbox Code Playgroud)
哪个回报: lat lon
我需要什么做的就是值lat
和lon
?(444
和555
)
Lio*_*ior 82
如果要迭代字典的键和值,请执行以下操作:
for key, value in data.items():
print key, value
Run Code Online (Sandbox Code Playgroud)
Pab*_*ruz 46
它给你带来了什么错误?
如果你这样做:
data = json.loads('{"lat":444, "lon":555}')
Run Code Online (Sandbox Code Playgroud)
然后:
data['lat']
Run Code Online (Sandbox Code Playgroud)
不应该给你任何错误.
使用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'])
Run Code Online (Sandbox Code Playgroud)
使用您的代码,这就是我要做的。我知道选择了答案,只是提供了其他选项。
data = json.loads('{"lat":444, "lon":555}')
ret = ''
for j in data:
ret = ret+" "+data[j]
return ret
Run Code Online (Sandbox Code Playgroud)
在此庄园中使用时,您将获得对象的键而不是值,因此可以通过将键用作索引来获取值。
有一个Py库,其中包含一个模块,可以方便地访问类似于Json的字典键值作为属性:https : //github.com/asuiu/pyxtension 可以将其用作:
j = Json('{"lat":444, "lon":555}')
j.lat + ' ' + j.lon
Run Code Online (Sandbox Code Playgroud)