Search code examples
muledataweaveanypoint-studiomule4anypoint-platform

How to condense a json object based on a key in dataweave


I have a json structure as follows:

[
  {
    "apiId": 18211158,
    "policyName0": "cors"
    
  },
  {
    "apiId": 18211158,
    "policyName1": "client-id-enforcement"
  },
  {
    "apiId": 18211150,
    "policyName0": "client-id-enforcement"
  },
  {
    "apiId": 18211162,
    "policyName0": "client-id-enforcement"
  },
  {
    "apiId": 18211162,
    "policyName1": "cors"
  },
  {
    "apiId": 18211162,
    "policyName2": "oauth"
  }
]

I need to transform this into following using dataweave 2.0

[
  {
    "apiId": 18211158
    "policyName0": "cors",
    "policyName1": "client-id-enforcement",
  },
  {
    "apiId": 18211150
    "policyName0": "client-id-enforcement",
  },
  {
    "apiId": 18211162
    "policyName0": "client-id-enforcement",
    "policyName1": "cors",
    "policyName2": "oAuth",

  }
]

Note that each apiID can have multiple policies and the policyName json attribute is generated and cal have values ranging from 1 to 9.

How can I condense the json based on apiID as the key in dataweave?


Solution

  • Try the below code

    %dw 2.0
    output application/json skipNullOn="everywhere"
    ---
    payload groupBy $."apiId" pluck $ map {
        apiId: $."apiId"[0],
        policyName0: $.policyName0[0],
        policyName1: $.policyName1[0],
        policyName1: $.policyName2[0]
    }
    
    

    Output As below

    [
      {
        "apiId": 18211158,
        "policyName0": "cors",
        "policyName1": "client-id-enforcement"
      },
      {
        "apiId": 18211150,
        "policyName0": "client-id-enforcement"
      },
      {
        "apiId": 18211162,
        "policyName0": "client-id-enforcement",
        "policyName1": "cors",
        "policyName1": "oauth"
      }
    ]