如何使用Python打印嵌套的JSON数据?

kmpatx3s  于 2023-10-21  发布在  Python
关注(0)|答案(3)|浏览(100)

我刚开始编程。我正在尝试使用Python脚本打印一些嵌套的JSON数据。
下面是一个JSON的例子:

{
"objects": [
        {
            "id": "1",
            "spec_version": "2.1",
            "type": "green",
            "extensions": {
                "extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba": {
                    "extension_type": "purple",
                    "id": "2",
                    "type": "yellow",
                    "created_at": "2023-09-26",
                    "updated_at": "2023-09-26",
                    "stix_ids": [
                        "3"
                    ],
                }
            }
       }
   ]
}

如果我必须在“extensions”中打印类似“extension_type”的内容,我该怎么做?我的Python脚本:

import json, requests 

url = "myUrl"

payload = {}
headers = {
  'Authorization': 'Auth',
  'Cookie': 'biscuit'
}

response = requests.request("GET", url, headers=headers, data=payload)
my_json = json.loads(response.text)

for data in my_json['objects'][0]['extensions']:
    print(data)

输出为:extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba我只能走这么远,我不知道如何访问“extension_type”并打印它。

rhfm7lfc

rhfm7lfc1#

我假设你知道extensions的密钥,但是下一个密钥是动态的,你不知道。在这种情况下,您可以按照以下步骤获取extension_type值:
由于my_json['objects'][0]['extensions']是一个dict,你可以使用下面的方法找到dict中的第一个(也是唯一一个)值:

ext = next(iter(my_json['objects'][0]['extensions'].values()))

然后简单地得到扩展名:

ext_type = ext['extension_type']

输出量:

'purple'
x3naxklr

x3naxklr2#

data = {
"objects": [
        {
            "id": "1",
            "spec_version": "2.1",
            "type": "green",
            "extensions": {
                "extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba": {
                    "extension_type": "purple",
                    "id": "2",
                    "type": "yellow",
                    "created_at": "2023-09-26",
                    "updated_at": "2023-09-26",
                    "stix_ids": [
                        "3"
                    ],
                }
            }
       }
   ]
}

您可以使用以下代码访问数据中的extension_type

data["objects"][0]["extensions"]["extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba"]["extension_type"]
0x6upsns

0x6upsns3#

另一种方法(适用于这个问题中的数据结构)是执行递归搜索,只寻找感兴趣的键-无论它在哪里。
举例来说:

def search(d, key):
    def _search(e):
        nonlocal key
        if isinstance(e, dict):
            if key in e:
                return e[key]
            for v in e.values():
                if (r := _search(v)) is not None:
                    return r
        elif isinstance(e, (list, tuple, set)):
            for v in e:
                if (r := _search(v)) is not None:
                    return r
    return _search(d)

data = {
    "objects": [
        {
            "id": "1",
            "spec_version": "2.1",
            "type": "green",
            "extensions": {
                "extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba": {
                    "extension_type": 'purple',
                    "id": "2",
                    "type": "yellow",
                    "created_at": "2023-09-26",
                    "updated_at": "2023-09-26",
                    "stix_ids": ["3"],
                }
            },
        }
    ]
}

print(search(data, 'extension_type'))

输出:

purple

相关问题