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?
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_elsematch: https://docs.mulesoft.com/mule-runtime/4.3/dataweave-pattern-matchingYou 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With