结合两个数组并使用Jolt进行变换

时间:2019-02-19 19:11:02

标签: jolt

在使用Jolt映射尝试将输入转换为必要格式时,我遇到了困难时期

输入JSON

header

输出JSON

{
  "data": [
    {
      "name": "Alcohol",
      "collection_id": 123,
      "properties": [
        {
          "name": "Tax",
          "property_id": "00001"
        },
        {
          "name": "Expenditure",
          "property_id": "00002"
        }
      ],
      "attributes": [
        {
          "name": "alcohol_tax",
          "attribute_id": "00011"
        },
        {
          "name": "alcohol_expenditure",
          "attribute_id": "00022"
        }
      ]
    }
  ]
}

我尝试了几种方法,使用一些规则来组合数组,但收效甚微。

其中一项规则

[
    {
        "name": "Alcohol",
        "collection_id": 123,
        "details": [{
                "property_name": "Tax",
                "property_id": "00001",
                "attribute_id": "00011"
            },
            {
                "property_name": "Expenditure",
                "property_id": "00002",
                "attribute_id": "00022"
            }
        ]
    }
]

正在将所有属性添加到所有集合中。我不知道为什么会这样,因为我以为&1.property_id []只会将特定集合中的项目添加到数组中,而不是所有集合中。真正感谢您提供有关此原因的任何帮助/线索。

1 个答案:

答案 0 :(得分:0)

请参阅以下解决方案:

  • [0]创建包装数组
  • [&1]使用各个数组的位置,因此结果将合并在details中,重要的部分是包装方括号,因此将其视为数组而不是文字。
[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "name": "[0].name",
          "collection_id": "[0].collection_id",
          "attributes": {
            "*": {
              "attribute_id": "[0].details.[&1].attribute_id"
            }
          },
          "properties": {
            "*": {
              "name": "[0].details.[&1].name",
              "property_id": "[0].details.[&1].property_id"
            }
          }
        }
      }
    }
  }
]

产生以下内容:

[
  {
    "name": "Alcohol",
    "collection_id": 123,
    "details": [
      {
        "attribute_id": "00011",
        "name": "Tax",
        "property_id": "00001"
      },
      {
        "attribute_id": "00022",
        "name": "Expenditure",
        "property_id": "00002"
      }
    ]
  }
]