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

Jolt转换需求:将指定字段移至对象根节点并修正输出格式

Jolt转换解决方案:观测项独立对象+队列序号字段

输入示例JSON

{
  "queues": [
    {
      "queueId": "Q1",
      "observations": [
        {
          "observationDate": "2024-05-01",
          "observationId": "O1",
          "requestedRoutingSkillIds": ["S1"],
          "otherField": "val1"
        },
        {
          "observationDate": "2024-05-02",
          "observationId": "O2",
          "requestedRoutingSkillIds": ["S2"],
          "otherField": "val2"
        }
      ]
    },
    {
      "queueId": "Q2",
      "observations": [
        {
          "observationDate": "2024-05-03",
          "observationId": "O3",
          "requestedRoutingSkillIds": ["S3"],
          "otherField": "val3"
        }
      ]
    }
  ]
}

正确Jolt转换规则

[
  {
    "operation": "shift",
    "spec": {
      "queues": {
        "*": {
          "observations": {
            "*": {
              // 为指定字段添加队列序号前缀(索引+1转1-based序号)
              "observationDate": "observationItems[#2][#1].queue#(+2)_observationDate",
              "observationId": "observationItems[#2][#1].queue#(+2)_observationId",
              "requestedRoutingSkillIds": "observationItems[#2][#1].queue#(+2)_requestedRoutingSkillIds",
              // 保留观测项其他原字段
              "*": "observationItems[#2][#1].&"
            }
          }
        }
      }
    }
  },
  // 将二维观测数组扁平化为一维,每个观测项作为独立对象
  {
    "operation": "flatten",
    "spec": {
      "observationItems": ""
    }
  }
]

输出结果

{
  "observationItems": [
    {
      "queue1_observationDate": "2024-05-01",
      "queue1_observationId": "O1",
      "queue1_requestedRoutingSkillIds": ["S1"],
      "otherField": "val1"
    },
    {
      "queue1_observationDate": "2024-05-02",
      "queue1_observationId": "O2",
      "queue1_requestedRoutingSkillIds": ["S2"],
      "otherField": "val2"
    },
    {
      "queue2_observationDate": "2024-05-03",
      "queue2_observationId": "O3",
      "queue2_requestedRoutingSkillIds": ["S3"],
      "otherField": "val3"
    }
  ]
}

核心Jolt语法说明

  • @:引用节点值。@代表当前节点的完整内容;@(n,key)可指定向上n层的key字段值(比如@(2,queueId)可获取队列的ID替代序号)。
  • &:引用当前节点的键名。比如*: "&"会原样保留原字段的键和值。
  • #:引用数组索引(从0开始)。#n表示向上n层的数组索引;#(+x)可对索引做加法(比如#(+2)是因为当前层级到queues数组差两层,索引+1转成1-based序号)。
  • *:通配符,用于遍历数组的每个元素或对象的每个键。
  • [#n]:指定数组位置,确保每个观测项被分配到独立的数组索引,避免字段值被合并为数组。

为什么之前的规则会合并字段?

之前的规则未给每个观测项指定独立的数组位置,直接将多个观测项的同名字段映射到同一个键下,Jolt默认会将多个值合并为数组。通过observationItems[#2][#1]给每个观测项分配唯一的二维数组位置,再用flatten转成一维数组,就能得到独立的观测对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:15:04