In previous post, transformed nested structure to flat. In this post example will do the reverse, transform flat structure back to original nested format, using nested groupBy, map, mapObject and orderBy.

Flat Json to Nested Json

1) nested group by OrderID, then ProductID, then Variant/Color.
2) order by OrderID, ProductID
3) Construct the final json using array, mean using [].

Had break the DataWeave code in incremental logical steps based on how I build them. Showing different steps, able to see how the intermediate json payload look like, before it become final json output. Good for understanding and reference again in the future.

Input Json:

After Step 1:

After Step 2:

After Step 3:

After Step 4:

After Step 5:

After Step 6:

Step 1:
This step simply group by OrderID.

Step 2:
This step add the 1st layer Orders.

Step 3:
This step add nested 2nd layer Items, under 1st Orders layer.

Step 4:
This step add nested 3rd layer Variants, under 2nd layer Items.

Step 5:
This step convert list of elements to array.

Step 6:
This step add orderBy OrderID, ProductID, Quantity.

Flat Json to Nested Xml

To transform from flat json to nested xml, can reused above steps until Step 4, change output to ‘application/xml’, and add orderBy.

Output of nested Xml:


DataWeave – Transform Flat Structure to Nested using groupBy, map, mapObject and orderBy
Tagged on:                 

7 thoughts on “DataWeave – Transform Flat Structure to Nested using groupBy, map, mapObject and orderBy

  • March 12, 2020 at 1:41 am

    This was exactly what I needed, thanks for the post

  • March 16, 2020 at 10:20 pm

    Hello, I am trying with similar payload, but its throwing an error in Step 2

    • March 16, 2020 at 10:20 pm

      Invalid input it says

    • May 19, 2020 at 10:44 pm

      i was using mule4, if copy exactly in mule4 should work, since i copy paste out from my output.

  • January 26, 2021 at 12:50 am

    Perfect, this is very helpful. Thank you.


Leave a Reply to Sarabh Cancel reply

Your email address will not be published. Required fields are marked *