首页 > 解决方案 > 仅在遍历 json 数据时获取字符串

问题描述

JSON:

{
    "status": "success",
    "data": {
        "9": {
            "1695056": {
                "id": "1695056",
                [...]
                },
                "csevents": {
                    "2807": {
                        "id": "2807",
                        "startdate": "2019-01-24 18:45:00",
                        "service_texts": [],
                        "eventTemplate": "1"
                    },
                    "2810": {
                        "id": "2810",
                        "startdate": "2019-01-31 18:45:00",
                        "service_texts": [],
                        "eventTemplate": "1"
                    }
                 }
            },
            "1695309": {
                "id": "1695309",
                [...]
                },
                "csevents": {
                    "3601": {
                        "id": "3601",
                        "startdate": "2019-05-17 18:45:00",
                        "service_texts": [],
                        "eventTemplate": "1"
                    }

我尝试使用python从“csevents”(“2807”,“2810”,3601“)中获取成员。问题是我在编码时不知道“9”(“1695056”,“1695309”)中的ID .

所以我尝试遍历“9”,然后遍历“csevents”,但如果我遍历“9”,我只会得到一个字符串,所以我不能再遍历“csevents”。

Python:

for whatever in json_object['data']['9']:
    for id in whatever['csevents']:
        print(id)

所以这行不通。有人知道我该如何解决吗?

谢谢

标签: pythonjsonapi

解决方案


必须清理您的 JSON 字符串才能使其正常工作,但查看您的解决方案似乎是您直接从您的dict,您应该使用的是.items().values()

for key, value in json_object['data']['9'].items():
    # We can use .keys() here since we only need the IDs from csevents
    csevent_keys = list(value['csevents'].keys())
    print(csevent_keys)

# Output
['2807', '2810']
['3601']

推荐阅读