This is a transformation using concept of Content Enricher Pattern:

Below example take 2 payloads that stored in 2 variables (input1, input2).
input1 is payload send from source system.
input2 is payload externally get from external system via API call.

input1 contain Orders and Items. Items contain ProductID but without UnitPrice.
input2 contain Products with ProductID and UnitPrice.
Below code filter input2 based on ProductID, then get UnitPrice for corresponding ProductID of input1.

"Orders": input1.Orders map(o, o_idx) ->{
	"OrderID": o.OrderID,
	"Items": o.Items map(i, i_idx) ->{	
		"ProductID": i.ProductID,
		(input2 filter($.ProductID == i.ProductID) map (p, p_idx) ->{
			"UnitPrice": p.UnitPrice
		}),
		"Quantity": i.Quantity
	}			
}


input1:

{
	"Orders": [{
			"OrderID": 2501,
			"Items": [{
					"ProductID": "P05",
					"Quantity": 1
				}
			]
		}, {
			"OrderID": 2502,
			"Items": [{
					"ProductID": "P05",
					"Quantity": 5
				}, {
					"ProductID": "P06",
					"Quantity": 1
				}
			]
		}, {
			"OrderID": 2503,
			"Items": [{
					"ProductID": "P07",
					"Quantity": 10
				}
			]
		}
	]
}


input2:

[
  {
    "ProductID": "P07",
    "UnitPrice": 120
  },
  {
    "ProductID": "P05",
    "UnitPrice": 50
  },
  {
    "ProductID": "P06",
    "UnitPrice": 80
  }
]


Merged output: Now payload is enriched with UnitPrice.

{
  "Orders": [
    {
      "OrderID": 2501,
      "Items": [
        {
          "ProductID": "P05",
          "UnitPrice": 50,
          "Quantity": 1
        }
      ]
    },
    {
      "OrderID": 2502,
      "Items": [
        {
          "ProductID": "P05",
          "UnitPrice": 50,
          "Quantity": 5
        },
        {
          "ProductID": "P06",
          "UnitPrice": 80,
          "Quantity": 1
        }
      ]
    },
    {
      "OrderID": 2503,
      "Items": [
        {
          "ProductID": "P07",
          "UnitPrice": 120,
          "Quantity": 10
        }
      ]
    }
  ]
}
DataWeave – Merge 2 Payloads using map and filter
Tagged on:                     

Leave a Reply

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