Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Existence in JSON Object (Mule 4)

I need to check the existence of a particular keyword in a JSON object and based on that, create a string. My sample dataweave 2.0 code is given below:

%dw 2.0
output application/json
var arr = {
    "ID": "100",
    "ProdId": "Prod",
    "ProdName": "ABC"
           }
---
if (arr pluck $$ joinBy ';' contains "ProdId") == true
    then (String: "Product") else
if (arr pluck $$ joinBy ';' contains "EmpId") == true
    then (String: "Employee") else null

Based on the value of the variable, I need to have different String values. What change is needed above to work?

like image 543
Triumph Spitfire Avatar asked Jan 31 '26 05:01

Triumph Spitfire


1 Answers

You can take advantage of the field existence operator ?:

%dw 2.0
output application/json
var o = {
    "ID": "100",
    "ProdId": "Prod",
    "ProdName": "ABC"
}
---
if (o.ProdId?) (String: "Product") else 
    if (o.EmpId?) (String: "Employee") else null

You can solve your problem with pattern-matching by using the match operator as well:

%dw 2.0
output application/json
var o = {
    "ID": "100",
    "ProdId": "Prod",
    "ProdName": "ABC"
}
---
"ProdId" match {
    case "ProdId" -> "String": "Product"
    case "EmpId"  -> "String": "Employee"
    else -> null
}

Here's the documentation:

  • if: https://docs.mulesoft.com/mule-runtime/4.3/dataweave-flow-control#control_flow_if_else
  • match: https://docs.mulesoft.com/mule-runtime/4.3/dataweave-pattern-matching

You also need to be aware that String is a type in DW, you must enclose it in quotes (" or ') to use as a field name.