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

如何用jq过滤JSON中Id不以DNSName开头的DNSNames条目

需求说明

过滤JSON数据中的DNSNames条目,移除那些满足「Id以该DNSName开头」的条目,保留剩余条目。

原始JSON数据

[
    {
        "Id": "9580cf2dd3161c0e33d8c04a4e84384e28784af65e55c1e84899d9da797902be",
        "NetworkSettings": {
            "Networks": {
                "nextcloud-aio": {
                    "IPAddress": "172.18.0.10",
                    "DNSNames": [
                        "nextcloud-aio-whiteboard",
                        "9580cf2dd316"
                    ]
                }
            }
        }
    }
]

原始jq命令及结果

执行以下jq查询:

jq -r '.[]|"\(.NetworkSettings.Networks[].IPAddress|select(length > 0) // "# no ip address:") \(if .NetworkSettings.Networks[].DNSNames != null then (.NetworkSettings.Networks[].DNSNames|join(" ")) else (.Name|sub("^/"; "")|sub("_1$"; "")) end)"'

得到结果:

172.18.0.10 nextcloud-aio-whiteboard 9580cf2dd316

修改后的jq命令及目标结果

通过添加过滤逻辑,移除与Id前缀匹配的DNSNames条目,修改后的jq命令如下:

jq -r '.[] | 
    . as $item |
    "\( $item.NetworkSettings.Networks[].IPAddress | select(length > 0) // "# no ip address:" ) \(
        if $item.NetworkSettings.Networks[].DNSNames != null then
            ( $item.NetworkSettings.Networks[].DNSNames | map( select( $item.Id | startswith(.) | not ) ) | join(" ") )
        else
            ( $item.Name | sub("^/"; "") | sub("_1$"; "") )
        end
    )"'

执行后得到目标结果:

172.18.0.10 nextcloud-aio-whiteboard

关键修改说明

  • 用. as $item保存当前对象,便于在嵌套结构中引用外层的Id字段
  • 通过map( select( $item.Id | startswith(.) | not ) )实现过滤:判断Id是否以当前DNSName开头,保留不符合该条件的条目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:42:35