从数组中获取多个对象中的重复字段值,并将其合并为一个对象。

huangapple go评论53阅读模式
英文:

JOLT- Get duplicated field value from multiple objects in array and make it one object

问题

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

I am attempting to transform JSON to JSON in the below example. I am getting some events from MQ with JSON payload with multiple objects with one common code. I am interested to get unique code as one JSON object. Below is the input data and expected output.

Input 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"
      }
   }
]

Expected Output

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

JOLT spec tried

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

Output getting

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

从数组中获取多个对象中的重复字段值,并将其合并为一个对象。

答案1

得分: 1

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "# ": "@(1,payload.code)"
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "$": "[#2].code"
      }
    }
  }
]
英文:

An option to group by a value is to keep that identifier(@(1,payload.code)) , which produces the value, on the right hand side such as

[
  { // 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"
      }
    }
  }
]

huangapple
  • 本文由 发表于 2023年4月20日 01:15:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定