Key Existence in JSON Object (Mule 4)

Viewed 2917

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?

2 Answers

I'm thinking about using the "keysOf" function (previously Object::keySet) and something like this:

%dw 2.0
output application/json
var arr = {
    "ID": "100",
    "ProdId": "Prod",
    "ProdName": "ABC"
           }
---
if (keysOf(arr) contains("ProdId" as Key)) "Product"
else if (keysOf(arr) contains("EmpId" as Key)) "Employee"
else "Not Recognized"

Note that "keysOf" returns an array of Key objects, not Strings.

EDIT:

A more dynamic approach can be this one:

%dw 2.0
output application/json
import firstWith from dw::core::Arrays
var arr = {
    "ID": "100",
    "ProdId": "Prod",
    "ProdName": "ABC"
           }
var myTypes = {
    ProdId: "Product",
    EmpId: "Employee"
}
var typeId = (keysOf(myTypes) firstWith (keysOf(arr) contains $)) as String
---
myTypes[typeId]

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:

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.

Related