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

如何用jq为JSON中所有'base'键添加完整路径键?

问题:为JSON中每个base键所在对象添加完整路径的path键

我需要遍历JSON数据,为每个包含base键的对象添加一个path键,值为该对象的完整路径。

输入JSON数据

{
  "entity": {
    "product": {
      "att": {
        "number_of_values": "Number of values"
      },
      "title": {
        "base": ["product", "products", "pdt", "pdts"]
      }
    },
    "rabbit": {
      "att": {
        "number_of_values": "Number of values"
      },
      "title": {
        "base": ["rabbit", "rabbits"]
      }
    }
  }
}

期望输出结果

{
  "entity": {
    "product": {
      "att": {
        "number_of_values": "Number of values"
      },
      "title": {
        "base": ["product", "products", "pdt", "pdts"],
        "path": "entity.product.title"
      }
    },
    "rabbit": {
      "att": {
        "number_of_values": "Number of values"
      },
      "title": {
        "base": ["rabbit", "rabbits"],
        "path": "entity.rabbit.title"
      }
    }
  }
}

尝试过的错误代码及结果

第一段代码

walk(if type == "object" and .base then  keys[] as $k | .base |= {path: $k} else . end)

执行结果:

{
  "entity": {
    "product": {
      "att": {
        "number_of_values": "Number of values"
      },
      "title": {
        "base": {
          "path": "base"
        }
      }
    },
    "rabbit": {
      "att": {
        "number_of_values": "Number of values"
      },
      "title": {
        "base": {
          "path": "base"
        }
      }
    }
  }
}

第二段代码

walk(if type == "object" and .base then  paths(..) as $v | .base |= {path: $v} else . end)

执行结果:

{
  "entity": {
    "product": {
      "att": {
        "number_of_values": "Number of values"
      },
      "title": {
        "base": {
          "path": [
            "base",
            3
          ]
        }
      }
    },
    "rabbit": {
      "att": {
        "number_of_values": "Number of values"
      },
      "title": {
        "base": {
          "path": [
            "base",
            1
          ]
        }
      }
    }
  }
}

解决方案

正确的jq代码如下:

paths(objects | has("base")) as $p
| setpath($p + ["path";]; ($p | join(".")))

代码说明

  1. paths(objects | has("base")):精准定位所有包含base键的对象的路径,得到类似["entity", "product", "title"]的路径数组。
  2. setpath($p + ["path";]; ($p | join("."))):对每个找到的路径,在对应对象中新增path键,值为路径数组用.拼接成的字符串,同时保留原base键的内容。

这段代码完全匹配期望的输出效果,不会破坏原有数据结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:31:17