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

如何按条件解析JSON:筛选匹配site.id的id与location.id字段

实现方案

不需要提前预知匹配数据的索引位置,直接遍历results数组做条件判断即可,完全可以覆盖索引不固定的场景,以下是可直接复用的实现逻辑:

核心逻辑

遍历接口返回的results列表中的每一个元素,逐个校验元素的site.id是否和你预先定义的目标值相等:

  • 如果确定接口只会返回1条匹配数据,找到第一个符合条件的元素后就可以终止遍历,节省性能
  • 如果可能存在多条匹配数据,就遍历完整个列表,收集所有符合条件的元素的目标字段

代码示例(Python)

# 预先定义的匹配目标值
TARGET_SITE_ID = 2

# 接口返回的原始响应
response = {
  "results": [
    {
      "id": 92,
      "site": {"id": 1},
      "location": {"id": 2}
    },
    {
      "id": 196,
      "site": {"id": 2},
      "location": {"id": 8}
    }
  ]
}

# 场景1:仅需获取第一条匹配数据
matched = None
for entry in response["results"]:
    # 用get写法兼容字段缺失的异常情况,避免报错
    if entry.get("site", {}).get("id") == TARGET_SITE_ID:
        matched = {
            "entry_id": entry["id"],
            "location_id": entry["location"]["id"]
        }
        break

# 输出结果:{'entry_id': 196, 'location_id': 8}
print(matched)

# 场景2:需要获取所有匹配数据
all_matched = []
for entry in response["results"]:
    if entry.get("site", {}).get("id") == TARGET_SITE_ID:
        all_matched.append({
            "entry_id": entry["id"],
            "location_id": entry["location"]["id"]
        })

# 输出结果:[{'entry_id': 196, 'location_id': 8}]
print(all_matched)

小提示:如果你能100%确定接口返回结构固定,不会出现字段缺失的情况,也可以直接用entry["site"]["id"]的写法替代get取值,代码会更简洁。

内容的提问来源于stack exchange,提问作者Alex Hoopes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 17:36:23