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

JQ转换JSON数组:无匹配时需返回空字符串而非空JSON

问题解决:用JQ提取指定条件的city值,无匹配时返回空字符串并保留结构

需求说明

处理JSON数据时,需要:

  • 从relations数组中提取满足primary: true且address.type: "project"的city值
  • 若没有符合条件的项,city设为空字符串""
  • 始终保留包含miscellenous字段的目标JSON结构(之前的写法在无匹配时返回空,不符合要求)

原始JSON示例

场景1:存在符合条件的项

{
  "miscellenous": "some data",
  "relations": [
    {
      "primary": false,
      "address": {
        "type": "office",
        "city": "New York"
      }
    },
    {
      "primary": true,
      "address": {
        "type": "project",
        "city": "London"
      }
    }
  ]
}

场景2:无符合条件的项

{
  "miscellenous": "some data",
  "relations": [
    {
      "primary": false,
      "address": {
        "type": "office",
        "city": "New York"
      }
    },
    {
      "primary": true,
      "address": {
        "type": "home",
        "city": "Paris"
      }
    }
  ]
}

现有代码的问题

之前的两种写法在有匹配时能得到正确结果,但无匹配时返回空JSON:

写法1(select)

.relations[] | select(.primary == true and .address.type == "project") | {miscellenous: .miscellenous, city: .address.city}

写法2(if-else)

if .relations[] | select(.primary == true and .address.type == "project") then {miscellenous: .miscellenous, city: .address.city} else {miscellenous: .miscellenous, city: ""} end

问题根源:当没有匹配项时,select返回空,导致整个表达式没有输出,而非构造包含空city的结构。


预期输出

场景1预期结果

{
  "miscellenous": "some data",
  "city": "London"
}

场景2预期结果

{
  "miscellenous": "some data",
  "city": ""
}

正确解决方案

基础版代码

{
  miscellenous: .miscellenous,
  city: (.relations[] | select(.primary == true and .address.type == "project") | .address.city) // ""
}

多匹配项处理版(取第一个匹配值)

如果relations数组中可能存在多个符合条件的项,用first函数取第一个结果:

{
  miscellenous: .miscellenous,
  city: (first(.relations[] | select(.primary == true and .address.type == "project") | .address.city) // "")
}

代码解释

  • (.relations[] | select(...) | .address.city):尝试提取符合条件的city,无匹配时返回null
  • // "":JQ的空值合并运算符,当左边结果为null或不存在时,自动替换为空字符串
  • 外层直接构造目标JSON结构,确保无论是否有匹配项,都会保留miscellenous字段并正确设置city值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:15:37