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

2024-05-16 23:29:03 发布

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

我需要从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”(name-1)中获取了“sid”。请帮帮我。你知道吗


Tags: nameinjsonforgetifresponsemy
3条回答

我画了一个简单的解决方案,也许可以满足你的需要。你知道吗

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'

希望有帮助!你知道吗

可以使用此代码段返回所有3sid值。。。。你知道吗

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')

这将在列表sids中存储所有相关的“sid”值。使用json库可以很容易地做到这一点,如下所示。 另外,我使用列表理解使代码更简洁。你知道吗

import json

d = json.loads(s)
sids = [customer['sid'] for customer in d['response'] if (customer['customName']=='name-3')]
print(sids)

输出

['aa88p2xfeh32e661']

If you want sid values from all the customers, you could use the following piece of code.

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"
            }
    ]
}
"""

相关问题 更多 >