我有Json:
[
{
"name":"Apple",
"price":2,
"have":0,
"max":36
},
{
"name":"Pineapple",
"price":5,
"have":6,
"max":17
}
]
我需要最快的功能,接收名称,并发送价格。例如,print(jsonname(“Apple”))是2。
P.S。请不要发布循环答案,我知道它们。我需要快速方法和方法名称
答案 0 :(得分:13)
这是一种简单的方法:
def function(json_object, name):
for dict in json_object:
if dict['name'] == name:
return dict['price']
如果您确定没有重复的名称,那么更有效(和 pythonic )的方法就是使用列表推导:
def function(json_object, name):
return [obj for obj in json_object if obj['name']==name][0]['price']
答案 1 :(得分:4)
from json import loads
json = """[
{
"name":"Apple",
"price":2,
"have":0,
"max":36
},
{
"name":"Pineapple",
"price":5,
"have":6,
"max":17
}
]"""
parsedJson = loads (json)
def jsonname (name):
for entry in parsedJson:
if name == entry ['name']:
return entry ['price']