从嵌套循环中提取数据

2024-04-27 13:19:12 发布

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

我有一个场景,在下面的条件下,我从json响应中提取数据:

我在json中循环并查找activeif active{}的值,然后在同一父数组下查找cls{}if typeis alpha1返回eces值(在本例中为260551)。 如果在通过json循环之后,没有active的值作为true或者active的值是true,但是在cls下的同一父数组中,type不是alpha1,那么返回notfound

在这里,我正确地得到了eces的值,但如何才能得到这个字段的值,以及addressc_mactivetype,然后构造所有提取数据的键值映射并保存在json文件中

以下是我尝试过的:

    found = False
    for di in d:
        if di.get('active', False):
            for cl in di.get('cls', []):
                if cl.get('type') == 'alpha1':
                    print(di['eces'])
                    found = True

    if not found:
        print("Not found")

所需的json输出:

{
    "res1": [{
        "eces": "260551",
        "res2": [{
            "c_m": 345,
            "clsfrmt": [
                {
                    "address": "{\"I_G\":\"CD\",\"I_D\":\"01\",\"I_Y\":\"C1\",\"I_XD\":\"04\",\"I_TY\":1,\"S_L\":\"https://testappsampler.com\",\"O_DC\":\"\"}",
                    "type": "Alpha"
                }
            ],
            "active": true
        }]
    }]
}

我一直在用这种结构创建json数据,任何帮助都会很好


Tags: 数据jsonfalsetruegetifaddresstype
1条回答
网友
1楼 · 发布于 2024-04-27 13:19:12

虽然我建议以某种适当的方式重构此代码,但这将以非常直接的方式创建映射:

import json

dump = []
for di in d:
    if di.get('active', False):
        for cl in di.get('cls', []):
            if cl.get('type') == 'alpha1':
                dump.append(
                {
                    "res1": [{
                        "eces": di['eces'],
                        "res2": [{
                            "c_m": di['c_m'],
                            "clsfrmt": [
                                {
                                    "address": di['cls'][0]['address'],
                                    "type": di['cls'][0]['type']
                                }
                            ],
                            "active": di['active']
                        }]
                    }]
                }
            )

s = json.dumps(dump) # this is your JSON string

Result

相关问题 更多 >