【问题标题】:How to search JSON object and extract the key/value pair?如何搜索 JSON 对象并提取键/值对?
【发布时间】:2022-01-21 21:09:18
【问题描述】:

我正在尝试搜索 JSON 对象并提取以下 'name''id' 的键/值。我想提取'name''id' 的所有实例:

{
"response": [
    {
        "additionalInfo": [],
        "id": "b6549916-b8e1-4131-b0be-f4a3daee26fc",
        "instanceTenantId": "5ffc97db91d68700c7ea827a",
        "name": "Global",
        "siteHierarchy": "b6549916-a8e1-4131-b0be-f4a3daee26fc",
        "siteNameHierarchy": "Global"
    },
    {
        "additionalInfo": [
            {
                "attributes": {
                    "addressInheritedFrom": "66284774-4ae4-42a1-b27c-68231c98d7db",
                    "type": "area"
                },
                "nameSpace": "Location"
            }
        ],
        "id": "4ffb292c-4cc8-444b-8978-61b97c6874db",
        "instanceTenantId": "5ffc97db91d68700c7ea827a",
        "name": "Peak Tester",
        "parentId": "66a84774-4ae4-42a1-b27c-68231c98d7db",
        "siteHierarchy": "b6549916-b8e1-4131-b0be-f4a3daee21fc/66a84774-4ae4-42a1-b27c-68231c98d7db/4ffb292c-4cc8-444b-8978-61b97c6874db",
        "siteNameHierarchy": "Global/Template Site/Peak Tester"
    }
]

}

我已经尝试了一些不起作用的方法。

for elements in site_info['response']:
for item in elements:
    if item == 'name':
        print(item)

这只会打印'name' 的输出而不是值。我想要值和键。

【问题讨论】:

  • 欢迎来到 Stack Overflow。在 Python 中,没有“JSON 对象”之类的东西。一旦你以任何正常的方式解析了 JSON,你所拥有的就是 一个普通的 dict,它的工作方式与你的 任何其他 dict 的工作方式相同 以任何其他方式创建
  • "我是一个 python 初学者,所以我很感激任何帮助" 如果你不知道基础知识,比如你可以用内置类型做的事情,那么你应该在尝试之前先学习一个教程解决自己的问题。
  • 感谢 Karl,感谢您的反馈。

标签: python json


【解决方案1】:

当您拥有key 并且需要value 时,您必须这样做:

>>> dictionary['key']
'value'

在你的情况下:

if item == 'name':
    print(item['name'])

无论如何,您都可以这样省略if 语句:

for item in elements:
    print(item['name'])

【讨论】:

  • @southcarolinaswampfox,很高兴为您提供帮助。无论如何,欢迎来到 StackOverflow!如果某个答案对您有用,您可以接受它以将其标记为有效答案。
  • 您不必遍历dict;你知道你想要的两个键,可以直接用if 'name' in elements: print(elements['name'])查看。
【解决方案2】:

我看到你已经有了答案,太好了。

data = { "response": [ {"name" : "fred"}, {"name" : "tom"}]} # data is a dictionary

arr = data['response'] # arr is a list of dictionaries

for i in arr:
    print('name', i['name']) # lookup the name value from each sub-dictionary

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多