You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python从指定嵌套列表结构中提取problems字段数据

Python提取嵌套列表中所有problems字段的方法

实现思路

  • 先把待处理的JSON格式字符串解析为Python的字典、列表嵌套对象
  • 逐层遍历嵌套结构:优先遍历最外层列表的每个元素,再遍历每个元素下ordination字段对应的子列表
  • 对ordination的每个子项做键存在性判断,存在problems字段就直接提取对应内容

实现代码

import json

# 待处理的JSON字符串
raw_data = '''
[{"ordination": [{"condition": "system_drive_free_space < 10000","match": true,"problems": [{"id": "disk_cleanup","point": "/remote_action/disk_cleanup/hgk5255sfghjkd516465s"}]},{"condition": "total_drive_free_space < 20000","match": true,"problems": [{ "id": "disk_cleanup","point": "/remote_action/disk_cleanup/h41525c274558hgfdbd3b"}]}]},{"ordination": [{"condition": "\"action:Get Startup Impact/HighImpactCount\" > 0","match": true}]},{"ordination": [{"condition": "average_network_response_time > 30000","match": true},{"condition": "network_availability_level != high","match": true}] }]
'''

# 解析为Python对象
data = json.loads(raw_data)
result = []

# 逐层遍历提取,保留要求的输出格式
for item in data:
    for ord_item in item.get("ordination", []):
        if "problems" in ord_item:
            result.append({"problems": ord_item["problems"]})

# 格式化打印结果
print(json.dumps(result, indent=2, ensure_ascii=False))

输出样例

[
  {
    "problems": [
      {
        "id": "disk_cleanup",
        "point": "/remote_action/disk_cleanup/hgk5255sfghjkd516465s"
      }
    ]
  },
  {
    "problems": [
      {
        "id": "disk_cleanup",
        "point": "/remote_action/disk_cleanup/h41525c274558hgfdbd3b"
      }
    ]
  }
]

如果需要直接提取所有problem对象的集合,只需要把遍历逻辑里的append行替换为result.extend(ord_item["problems"])即可。

内容的提问来源于stack exchange,提问作者code analyzer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:15:04