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

如何编写JQ表达式筛选与form.state匹配的xls数组城市

JQ表达式筛选匹配指定state的城市

目标JSON结构

{
    "form" : {
        "state" : "MH"
    },
    "xls":[
        {
            "state": "MH",
            "channel" : 1,
            "city": "Pune"
        },{
            "state": "MH",
            "channel" : 1,
            "city": "Nashik"
        },{
            "state": "MH",
            "channel" : 2,
            "city": "Solapur"
        },{
            "state": "MH",
            "channel" : 2,
            "city": "Nagpur"
        },{
            "state": "KAR",
            "channel" : 1,
            "city": "Mysore"
        },{
            "state": "KAR",
            "channel" : 1,
            "city": "Bijapur"
        },{
            "state": "KAR",
            "channel" : 2,
            "city": "Bellary"
        },{
            "state": "KAR",
            "channel" : 2,
            "city": "Mangalore"
        }
    ]
}

需求

筛选出xls数组中state值与顶层form.state一致的所有城市名称。

问题分析

你尝试的表达式无法生效,是因为遍历xls[]时,当前上下文切换为数组内的单个对象,此时.form.state会试图从当前对象中获取form属性,而非顶层的form节点。

简洁解决方案

方案1:用变量捕获目标state值(推荐)

先将顶层的form.state存入变量,后续遍历数组时直接引用该变量,逻辑清晰且高效:

.form.state as $targetState | .xls[] | select(.state == $targetState) | .city

方案2:直接引用根节点上下文

使用$符号引用JSON根节点,无需额外变量:

.xls[] | select(.state == $form.state) | .city

执行结果

两种方案运行后都会输出匹配的城市:

"Pune"
"Nashik"
"Solapur"
"Nagpur"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:58:26