我需要从JSON中获取“ sid”值
{
"response": [
{
"customName": "name-1",
"sid": "1247azc08belr2q4"
},
{
"customName": "name-2",
"sid": "zz63p2xxeh32b661"
},
{
"customName": "name-3",
"sid": "aa88p2xfeh32e661"
}
]
}
我试图做
customName_1 = 'name-1'
customName_2 = 'name-2'
customName_3 = 'name-3'
for name in My_JSON['response']:
if name['customName'] == customName_3:
print(name['sid'])
else:
print('Cant get sid')
但是它不起作用,因为我从第一个“ customName”(名称-1)中获取了“ sid”。帮我这个忙。
答案 0 :(得分:1)
这会将所有相关的'sid'值存储在列表sids
中。您可以使用json
库轻松完成此操作,如下所示。
另外,我使用列表推导使您的代码更简洁。
import json
d = json.loads(s)
sids = [customer['sid'] for customer in d['response'] if (customer['customName']=='name-3')]
print(sids)
输出:
['aa88p2xfeh32e661']
如果要从所有客户那里获取
sid
值,则可以使用以下代码。
sids = [customer['sid'] for customer in d['response']]
s = """
{
"response": [
{
"customName": "name-1",
"sid": "1247azc08belr2q4"
},
{
"customName": "name-2",
"sid": "zz63p2xxeh32b661"
},
{
"customName": "name-3",
"sid": "aa88p2xfeh32e661"
}
]
}
"""
答案 1 :(得分:1)
您可以使用此代码段返回所有3个sid
值。...
MY_JSON = {
"response": [
{
"customName": "name-1",
"sid": "1247azc08belr2q4"
},
{
"customName": "name-2",
"sid": "zz63p2xxeh32b661"
},
{
"customName": "name-3",
"sid": "aa88p2xfeh32e661"
}
]
}
names = ["name-1", "name-2", "name-3"];
for name in MY_JSON['response']:
if name['customName'] in names:
print(name['sid'])
else:
print('Cant get sid')
答案 2 :(得分:1)
我草拟了可能会满足需要的简单解决方案。
def grab_item_by_attr(lst, attr_name, attr_value):
result = None
for item in lst:
if item[attr_name] == attr_value:
result = item
return result
调用它时,结果将是您需要的项目:
>>> item = grab_item_by_attr(data['response'], 'customName', 'name-3')
>>> item
{'customName': 'name-3', 'sid': 'aa88p2xfeh32e661'}
>>> item['sid']
'aa88p2xfeh32e661'
希望对您有帮助!