Warm tip: This article is reproduced from stackoverflow.com, please click
dataweave json mule mulesoft

Merge elements in JSON within Mule 4

发布于 2020-04-23 12:28:44

I have the following SQL Server select query:

SELECT s.RefId
          ,s.LocalId
          ,s.StateProvinceId
          ,s.SchoolName
          ,e.Email
          ,e.EmailType
      FROM SchoolInfo s
      LEFT OUTER JOIN SchoolEmail e
      ON    e.SchoolRefId = s.RefId
      WHERE s.RefId = :ref_id

Converted to JSON in DataWeave:

%dw 2.0
output application/json
---
payload

Output:

[
  {
    "StateProvinceId": "SA",
    "RefId": "7FDF722B-6BBA-4BF0-8205-A5380B269EF1",
    "EmailType": "prm",
    "LocalId": "1",
    "SchoolName": "Steve's School",
    "Email": "steven@email.com"
  },
  {
    "StateProvinceId": "SA",
    "RefId": "7FDF722B-6BBA-4BF0-8205-A5380B269EF1",
    "EmailType": "sec",
    "LocalId": "1",
    "SchoolName": "Steve's School",
    "Email": "test@gmail.com"
  }
]

But I wish to have it merged by the common elements to generate the desired output of:

{
  "RefId": "7FDF722B-6BBA-4BF0-8205-A5380B269EF1",
  "LocalId": "1",
  "StateProvinceId": "SA",
  "SchoolName": "Steve's School",
  "Emails": [
    {
      "Email": "steven@email.com",
      "EmailType": "prm"
    },
    {
      "Email": "test@gmail.com",
      "EmailType": "sec"
    }
  ]
}

How can I do that in Mule 4?

Thanks, Steve

Questioner
Steve
Viewed
32
Salim Khan 2020-02-09 11:36

Or even this

%dw 2.0
output application/json
var Emails =  
    "Emails": payload map {
      Email: $.Email,
      EmailType: $.EmailType
}

---
payload distinctBy($.StateProvinceId) map {
  StateProvinceId: $.StateProvinceId,
  RefId: $.RefId,
  Emails:  Emails.Emails
}