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

技术需求:将jq数组内部值转为数组外部新键(含示例)

使用jq将tags数组中带key的项转为资产元素的字段

我刚好处理过类似的JSON转换需求,这里有个简洁的jq命令可以完美实现你想要的效果:

.data.assets |= map(
  . + (.tags | map(select(.key != null) | {(.key): .value}) | add)
)

命令细节解释

  • .data.assets |= map(...):定位到data下的assets数组,对数组内的每个资产元素执行转换逻辑
  • . + (...):将原资产对象和新生成的键值对对象合并,完整保留原有所有字段结构
  • .tags | map(select(.key != null) | {(.key): .value}):遍历当前资产的tags数组,筛选出key不为null的项,把每个符合条件的项转换成{key值: value值}的独立对象
  • | add:把多个零散的键值对对象合并成一个完整对象,确保能一次性合并到原资产对象中

实际验证示例

假设你的输入JSON文件名为input.json,执行以下命令即可得到预期输出:

jq '.data.assets |= map(. + (.tags | map(select(.key != null) | {(.key): .value}) | add))' input.json

输入示例(简化版):

{
  "data": {
    "assets": [
      {
        "organizationId": "1056bda9-2598-4fdf-bd99-db3924464a75",
        "tags": [
          {"value": "v1", "key": "product-api-version", "mutable": false},
          {"value": "sourcing", "key": null, "mutable": true}
        ],
        "type": "rest-api"
      }
    ]
  }
}

输出结果:

{
  "data": {
    "assets": [
      {
        "organizationId": "1056bda9-2598-4fdf-bd99-db3924464a75",
        "tags": [
          {"value": "v1", "key": "product-api-version", "mutable": false},
          {"value": "sourcing", "key": null, "mutable": true}
        ],
        "type": "rest-api",
        "product-api-version": "v1"
      }
    ]
  }
}

这个方案不管tags里有多少个带key的项,都能一次性批量处理,完全满足你保留原结构的要求。

内容的提问来源于stack exchange,提问作者Naveen K Reddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:02:11