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

如何编写jq过滤器:按需保留forecast字段并过滤内容,保留其他字段

解决方案

你需要的jq语句可以通过条件判断结合字段处理实现,既能保留所有同级元素,又能按需生成有效的forecast字段:

with_entries(
  if .key == "forecast" then
    .value = (.value.solar | { scale, energy }) | select(.value != null)
  else
    .
  end
)

代码逻辑说明

  1. with_entries:遍历输入对象的所有键值对,逐个处理
  2. 遇到forecast键时:
    • 提取其solar字段下的scale和energy,生成新的对象
    • 如果处理后的值为null(比如solar不存在、forecast是空对象),就通过select删除这个forecast键
  3. 其他键(比如siteTitle)直接保留,不做修改

场景验证

场景1:forecast存在且包含solar数据

输入:

{
  "siteTitle": "My Solar Site",
  "forecast": {
    "solar": {
      "scale": 1.2,
      "energy": 500,
      "extraField": "ignore"
    },
    "wind": {}
  }
}

输出:

{
  "siteTitle": "My Solar Site",
  "forecast": {
    "solar": {
      "scale": 1.2,
      "energy": 500
    }
  }
}

场景2:forecast为空对象

输入:

{
  "siteTitle": "My Solar Site",
  "forecast": {}
}

输出:

{
  "siteTitle": "My Solar Site"
}

场景3:forecast完全不存在

输入:

{
  "siteTitle": "My Solar Site"
}

输出:

{
  "siteTitle": "My Solar Site"
}

如果你偏好更直观的写法,也可以用以下语句,逻辑完全一致:

. + (
  if .forecast?.solar then
    { forecast: { solar: { scale: .forecast.solar.scale, energy: .forecast.solar.energy } } }
  else
    {}
  end
) | del(.forecast | select(. == {} or .solar == null))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 22:46:14