1

Below example contains same key "row". There may be thousands of such objects. I need an optimal solution in converting below object:

{
    "row":{
        "name": "abc"
    },
    "row":{
        "school": "pqr"
    }
}

Required output:

{
    "rows":
    [
        {
            "name": "abc"
        },
        {
            "school": "pqr"
        }
    ]
}
aled
  • 21,330
  • 3
  • 27
  • 34
  • What is "optimal" for you exactly? You need to define the criteria to evaluate answers and decide which is more optimal. – aled Apr 18 '23 at 11:36
  • Optimal in the sense, looking for a less expensive solution. Because around 7000 objects will be there and key for all of them as 'row' – Mule-Newbie Apr 19 '23 at 12:32
  • Again, expensive in what sense? A specific metric? Any of the answers fails to meet a criteria? – aled Apr 19 '23 at 13:13
  • The answers are perfect and works fine. Thank you for that; Could you point me to the one which will have less impact on memory and will be faster. – Mule-Newbie Apr 19 '23 at 13:58
  • No. I can make a guess it is the answer using the multi-value selector because it uses only one simple operation, but to actually be sure implies performance testing in real conditions (ie similar payloads and hardware/software to what you expect in production), taking measurements of the metrics that you are interested and analyzing them. – aled Apr 19 '23 at 14:24

2 Answers2

4

Just make use of the Multi-value Selector to get all keys with same key name:

https://docs.mulesoft.com/dataweave/2.4/dataweave-selectors

%dw 2.0
output application/json
---
rows: payload.*row
aled
  • 21,330
  • 3
  • 27
  • 34
StackOverflowed
  • 719
  • 3
  • 7
1

Here groupBy will help to group similar keys and pluck will convert object to array.

  • Solution 1: using mapObject(). This is a better solution since 2 plucks are eliminated here with respect to the second solution below.
%dw 2.0
output application/json
---
(payload groupBy $$) mapObject (($$): ($ pluck $))

Input

{
    "row":{
        "name": "abc"
    },
    "row":{
        "school": "pqr"
    }
}

Output

[
  {
    "row": [
      {
        "name": "abc"
      },
      {
        "school": "pqr"
      }
    ]
  }
]
  • Solution 2: using map()

If you want rows as hardcoded key then replace (($ pluck $$)[0]):($ pluck $) with ("rows"):($ pluck $)

%dw 2.0
output application/json
---
(payload groupBy $$)pluck $ map{
    (($ pluck $$)[0]):($ pluck $)
}
aled
  • 21,330
  • 3
  • 27
  • 34
Karthik
  • 2,181
  • 4
  • 10
  • 28