user12277274
user12277274

Reputation: 109

Fetching key:value pair from array object in mule4

I want to retrieve key value pair from json array object. I am trying to build a dynamic where clause with the input. If the key value is same in the array then I want to should use it with "IN" operator else I want to use "AND". Explaining both scenarios using two examples

Input1:

"values": [
{
  "id": "123"
},
{
  "id": "455"
}

]

Expected Output:

**"Where id in ('123','455')"**

Input2:

"values": [
{
  "id": "123"
},
{
  "name": "abc"
}

]

Expected Output:

**"Where id = '123' and name = 'abc'**

Thanks in advance

Upvotes: 1

Views: 1696

Answers (3)

Salim Khan
Salim Khan

Reputation: 4303

Christian's approach , using keyset

%dw 2.0
import * from dw::core::Objects
import * from dw::core::Arrays
output application/json
var firstKey = keySet(payload.values[0])[0]
var sameKeys = payload.values every ((item) -> keySet(item)[0] == firstKey)
---
if (sameKeys) 
    "Where " ++ firstKey ++ " in ('" ++ (payload.values[firstKey] joinBy "','") ++ "')" 
else 
    "Where " ++ (payload.values map ((item, index) -> keysOf(item)[0] ++ " = '" ++ valuesOf(item)[0] ++ "'") joinBy  " and ")

Upvotes: 1

Christian Chibana
Christian Chibana

Reputation: 568

Check if all keys are the same to differentiate the cases.

You can use the joinBy function with "','" or " and " to separate the values.

%dw 2.0
import * from dw::core::Arrays
output application/json
var firstKey = keysOf(payload.values[0])[0]
var sameKeys = payload.values every ((item) -> keysOf(item)[0] == firstKey)
---
if (sameKeys) 
    "Where " ++ firstKey ++ " in ('" ++ (payload.values[firstKey] joinBy "','") ++ "')" 
else 
    "Where " ++ (payload.values map ((item, index) -> keysOf(item)[0] ++ " = '" ++ valuesOf(item)[0] ++ "'") joinBy  " and ")

Upvotes: 0

Dale
Dale

Reputation: 1301

This should get you moving on the right path.

%dw 2.0
import * from dw::core::Arrays
output application/json

var values = 
    [
        {
            "id": "123"
        },
        {
            "id": "abc"
        }
    ]

---

if ( (values countBy ($.id != null)) > 1 )
    "in"
else if ( (values countBy ($.id != null)) == 1 )
    "and"
else
    "idk"

Upvotes: 1

Related Questions