json JOLT-从数组中的多个对象中获取重复的字段值并使其成为一个对象

6l7fqoea  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(157)

我试图在下面的例子中将JSON转换为JSON。我从MQ中获取一些事件,其中JSON有效负载具有多个对象,具有一个公共代码。我有兴趣将唯一代码作为一个JSON对象。下面是输入数据和预期输出。

输入JSON格式

[
   {
      "name":"data1",
      "event":"MAP",
      "payload":{
         "event":"ADDED",
         "code":"ABC"
      }
   },
   {
      "name":"data2",
      "event":"MAP",
      "payload":{
         "event":"ADDED",
         "code":"ABC"
      }
   },
   {
      "name":"data3",
      "event":"MAP",
      "payload":{
         "event":"ADDED",
         "code":"ABC"
      }
   },
   {
      "name":"data4",
      "event":"MAP",
      "payload":{
         "event":"ADDED",
         "code":"DEF"
      }
   },
   {
      "name":"data5",
      "event":"MAP",
      "payload":{
         "event":"ADDED",
         "code":"DEF"
      }
   },
   {
      "name":"data6",
      "event":"MAP",
      "payload":{
         "event":"ADDED",
         "code":"DEF"
      }
   }
]

预期产出

[
   {
      "code":"ABC"
   },
   {
      "code":"DEF"
   }
]

已尝试JOLT规范

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "@payload.code": "[&1].code"
      }
    }
  }
]

输出获取

[
   {
      "code":"ABC"
   },
   {
      "code":"ABC"
   },
   {
      "code":"ABC"
   },
   {
      "code":"DEF"
   },
   {
      "code":"DEF"
   },
   {
      "code":"DEF"
   }
]

nbysray5

nbysray51#

按值分组的一个选项是将生成值的标识符(@(1,payload.code))保留在右侧,例如

[
  { // get unique keys "ABC" and "DEF"
    "operation": "shift",
    "spec": {
      "*": {
        "# ": "@(1,payload.code)"
      }
    }
  },
  { // create array of objects which contain attributes with values taken from the previously derived keys  
    "operation": "shift",
    "spec": {
      "*": {
        "$": "[#2].code"
      }
    }
  }
]

相关问题