JOLT 排列规范

问题描述 投票:0回答:2

您能帮我编写以下 JOLT 规范吗?

输入:

{
  "title": [
    "vsnu",
    "anothervsnu"
  ],
  "anothertitle": [
    "vsnu",
    "anothervsnu"
  ]
}

预期输出:

{
  "Response": [
    {
      "head": "title",
      "name": "vsnu"
    },
    {
      "head": "title",
      "name": "anothervsnu"
    },
    {
      "head": "anothertitle",
      "name": "vsnu"
    },
    {
      "head": "anothertitle",
      "name": "anothervsnu"
    }
  ]
}

过去三天我一直陷在这个困境中。请帮我解决这个问题。 我希望上面的问题能够解释我的期望,我写这篇文章只是因为 StackOverflow 显示了验证错误消息。

提前致谢。

javascript java json transformation jolt
2个回答
0
投票

您只需要两个迭代器,一个迭代器位于输入的键上,另一个迭代器位于属性的数组上。

function buildObject(o) {
    var result = [];

    Object.keys(o).forEach(function (k) {
        o[k].forEach(function (a) {
            result.push({ head: k, name: a });
        });
    });
    return { Response: result };
}

var input = { "title": ["vsnu", "anothervsnu"], "anothertitle": ["vsnu", "anothervsnu"] },
    output = buildObject(input);

document.write('<pre>' + JSON.stringify(output, 0, 4) + '</pre>');


0
投票

因为 Jolt“shift”一次处理一项,所以很难写入地图数组的输出。

可以做,但是需要两班倒。第一个构建“head”和“name”的并行数组,第二个使用并行数组中的索引号将它们转入响应数组。

规格

[
  {
    "operation": "shift",
    "spec": {
      "*": { // title or anothertitle
        "*": { // array index
          "*": { // actual array value "vsnu"
            "$2": "head[]", // for each array value grab a copy of the "title"
            "$": "name[]"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "head": {
        "*": "Response[&].head"
      },
      "name": {
        "*": "Response[&].name"
      }
    }
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.