Python 3.10如何提取函数返回类JSON结构中所有custom_id值
提取嵌套结构中所有
custom_id值的方法 以下代码基于Python 3.10环境验证可用。
你拿到的函数返回结果是嵌套列表+字典结构,所有custom_id字段都位于外层列表元素的components子列表中,直接遍历提取即可。
先将返回结果赋值给变量存储:
resp = [{'type': 1, 'components': [{'type': 2, 'style': 1, 'label': 'She/Her', 'custom_id': 'She/Her'}, {'style': 1, 'label': 'He/Him', 'custom_id': 'He/Him', 'type': 2}]}]
写法1:基础循环(可读性强,推荐新手使用)
custom_id_list = [] # 遍历外层列表的每个块元素 for block in resp: # 遍历当前块下的所有组件,用get避免KeyError for component in block.get('components', []): # 组件存在custom_id字段时就追加到结果列表 if 'custom_id' in component: custom_id_list.append(component['custom_id'])
执行后custom_id_list的输出为:
['She/Her', 'He/Him']
写法2:列表推导式(代码简洁)
如果习惯Pythonic的短写法,可以直接用列表推导式实现完全相同的逻辑:
custom_id_list = [comp['custom_id'] for block in resp for comp in block.get('components', []) if 'custom_id' in comp]
补充说明:如果后续该函数返回的结构层级加深,比如
components内部还嵌套子组件列表,可以写递归函数遍历所有字典层级提取目标键值。针对你当前给出的返回结构,上述两种写法完全够用。
内容的提问来源于stack exchange,提问作者Breezicus
相关产品推荐
相关产品推荐

