通过键值对进行JOLT变换展平嵌套数组

时间:2018-10-25 00:47:25

标签: json jolt

我正在尝试转换以下JSON

{
  "data": {
    "keyvalues": [
      {
        "key": "location",
        "value": "sydney, au"
      },
      {
        "key": "weather",
        "value": "sunny"
      }
    ]
  },
  "food": {
    "name": "AllFoods",
    "date": "2018-03-08T09:35:17-03:00",
    "count": 2,
    "food": [
      {
        "name": "chocolate",
        "date": "2018-03-08T12:59:58-03:00",
        "rating": "10",
        "data": null
      },
      {
        "name": "hot dog",
        "date": "2018-03-08T09:35:17-03:00",
        "rating": "7",
        "data": {
          "keyvalues": [
            {
              "key": "topping",
              "value": "mustard"
            },
            {
              "key": "BUN type",
              "value": "toasted"
            },
            {
              "key": "servings",
              "value": "2"
            }
          ]
        }
      }
    ]
  }
}

使用JOLT(在NIFI中),可以像这样简单一些。将第一个顶级food属性(namedatecount)放入header,然后向上拉嵌套的food数组,然后将food.data.keyvalues展平为dict / hashmap。

{
  "header": {
    "location": "sydney, au",
    "weather": "sunny",
    "date": "2018-03-08",
    "count": 2
  },
  "foods": [
    {
      "name": "chocolate",
      "date": "2018-03-08T12:59:58-03:00",
      "rating": "10"
    },
    {
      "name": "hot dog",
      "date": "2018-03-08T09:35:17-03:00",
      "rating": "7",
      "topping": "mustard",
      "bun_type": "toasted",
      "servings": "2"
    }
  ]
}

我已经开始使用第一个data部分,但是我不确定如何处理嵌套的food元素。顶层food信息需要移至header部分,而第二层food数组则需要平坦化data.keyvalues

当前规范...(仅处理顶部的data.keyvalues

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "keyvalues": {
          "*": { "@value": "@key" }
        }
      }
    }
  }
]

1 个答案:

答案 0 :(得分:2)

规格

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "keyvalues": {
          "*": {
            "value": "header.@(1,key)"
          }
        }
      },
      "food": {
        "date": "header.date",
        "count": "header.count",
        "food": {
          "*": {
            "name": "foods[&1].name",
            "date": "foods[&1].date",
            "rating": "foods[&1].rating",
            "data": {
              "keyvalues": {
                "*": {
                  "value": "foods[&4].@(1,key)"
                }
              }
            }
          }
        }
      }
    }
  }
]