Python,JSON。如何从具有相同名称的键中获取值?

时间:2019-11-02 06:08:00

标签: python json

我需要从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”。帮我这个忙。

3 个答案:

答案 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'

希望对您有帮助!