Java Jolt:找不到适合我的转换的规范

Java Jolt: can't find proper spec for my transformation

我正在为 Jolt 转型而苦苦挣扎: 这是我的输入 JSON

{
  "bloc1-1": {
    "bloc1-2": [
      {
        "key": "key1",
        "value": "value1-1"
      },
      {
        "key": "key2",
        "value": "value1-2"
      }
    ]
  },
  "bloc2-1": {
    "bloc2-2": [
      {
        "key": "key1",
        "value": "value2-1"
      },
      {
        "key": "key2",
        "value": "value2-2"
      },
      {
        "key": "key3",
        "value": "value2-3"
      }
    ]
  }
}

这就是我所期待的

{
  "bloc1-key1" : "value1-1",
  "bloc1-key2" : "value1-2",
  "bloc2-key1" : "value2-1",
  "bloc2-key2" : "value2-2",
  "bloc2-key3" : "value2-3"
}

我尝试了以下规范,但我不知道如何在 RHS 中为键添加前缀(@ 应该是第一个字符)

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "value": "@(1,key)"
          }
        }
      }
    }
  }
]

明白了

{
  "key1" : [ "value1-1", "value2-1" ],
  "key2" : [ "value1-2", "value2-2" ],
  "key3" : "value2-3"
}

如有任何帮助,我们将不胜感激

下面的规范应该可以解决问题:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "": "keyParts1",
            "key": "keyParts2",
            "value": "values"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "keyParts1": {
        "*": "[#1].part1"
      },
      "keyParts2": {
        "*": "[#1].part2"
      },
      "values": {
        "*": "[#1].value"
      }
    }
  },
  {
    "operation": "modify-default-beta",
    "spec": {
      "*": {
        "newKey": "=split('-', @(1,part1))",
        "newKeyFirst": "@(1,newKey[0])",
        "newKeyComplete": "=concat(@(1,newKeyFirst),'-',@(1,part2))"
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "value": "@(1,newKeyComplete)"
      }
    }
  }
]

尝试分别应用每个操作(例如在 demo app 中)。

查看 jolt 文档的链接和来自 this answer

的示例

分步说明:

第一个 "shift" 转换将最终结果的组件放在单独的数组中:

{
  "keyParts1" : [ "bloc1-1", "bloc1-1", "bloc2-1", "bloc2-1", "bloc2-1" ],
  "keyParts2" : [ "key1", "key2", "key1", "key2", "key3" ],
  "values" : [ "value1-1", "value1-2", "value2-1", "value2-2", "value2-3" ]
}

以上操作让我们将最终结果的每个组成部分定位在所需结果的正确索引中。 请注意,每个数组都具有相同的大小。 在第二个操作中,我们使用 # 运算符按索引对每个数组元素进行分组。看着 docs [#1] 可以翻译成:

"Go up one level and ask that node how many matches it has had before finding the current element".

上面的节点是一个数组,因此对于第 3 个数组元素,它将是数组索引 2

[
  ...
  {
    "part1" : "bloc2-1",
    "part2" : "key1",
    "value" : "value2-1"
  }
  ...
]

在第三个操作中我假设所需结果的键是 "blocX-Y" 键的 "blocX" 子串与"key" 值。这就是我使用 "modify-default-beta" 的原因。看看 the example from the demo app 数组的五个元素中的每一个都与第三个数组元素类似地进行转换:

[
  ...
  {
    "part1" : "bloc2-1",
    "part2" : "key1",
    "value" : "value2-1",
    "newKey" : [ "bloc2", "1" ],
    "newKeyFirst" : "bloc2",
    "newKeyComplete" : "bloc2-key1"
  }
  ...
]

最后一个操作从第三个操作的输出中产生了期望的结果。