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

使用Jolt规范去除嵌套JSON数组重复项并修正字段映射

Jolt规范解决方案:去重subitems并转换状态值

核心需求

  • 去除subitems数组中的重复条目
  • 将状态值"P"转换为"Present","N"转换为"NotPresent"

输入JSON

{
  "items": [
    {
      "id": "1",
      "subitems": [
        {
          "subId": "A",
          "status": "P"
        },
        {
          "subId": "A",
          "status": "P"
        },
        {
          "subId": "B",
          "status": "N"
        }
      ]
    }
  ]
}

尝试的Jolt规范(存在去重问题)

[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "items": {
        "*": {
          "subitems": {
            "*": {
              "status": {
                "P": "Present",
                "N": "NotPresent"
              }
            }
          }
        }
      }
    }
  }
]

预期输出JSON

{
  "items": [
    {
      "id": "1",
      "subitems": [
        {
          "subId": "A",
          "status": "Present"
        },
        {
          "subId": "B",
          "status": "NotPresent"
        }
      ]
    }
  ]
}

修正后的Jolt规范

[
  // 转换状态值
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "items": {
        "*": {
          "subitems": {
            "*": {
              "status": {
                "P": "Present",
                "N": "NotPresent"
              }
            }
          }
        }
      }
    }
  },
  // 按subId分组实现去重
  {
    "operation": "shift",
    "spec": {
      "items": {
        "*": {
          "id": "items[&1].id",
          "subitems": {
            "*": {
              "@": "items[&3].tempSubitems[&1].&"
            }
          }
        }
      }
    }
  },
  // 重组去重后的subitems数组
  {
    "operation": "shift",
    "spec": {
      "items": {
        "*": {
          "id": "items[&1].id",
          "tempSubitems": {
            "*": {
              "@": "items[&2].subitems[]"
            }
          }
        }
      }
    }
  },
  // 清理临时字段
  {
    "operation": "remove",
    "spec": {
      "items": {
        "*": {
          "tempSubitems": ""
        }
      }
    }
  }
]

规范解释

  1. 状态转换:通过modify-overwrite-beta操作,直接替换subitems中每个条目的status字段值。
  2. 分组去重:利用shift操作将subitems条目存入以subId为键的临时对象tempSubitems,借助对象键的唯一性自动剔除重复项。
  3. 重组数组:再次使用shift从临时对象中提取值,重新组装为符合预期结构的subitems数组。
  4. 清理临时字段:用remove操作删除临时生成的tempSubitems,保证输出结构干净。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:42:05