仅在遍历json d时获取字符串

2024-05-12 23:33:24 发布

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

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)

所以这不管用。有人知道我怎么解决这个问题吗

谢谢


Tags: inidjson编码fordatastatusservice
1条回答
网友
1楼 · 发布于 2024-05-12 23:33:24

必须清理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']

相关问题 更多 >