Key-Value Pair Selector (.&myKey)

Key-Value Pair Selector (.&myKey)

The & selector acts on arrays and objects. & retrieves both the keys and values of all matching keys pairs in the current context. These are returned as an object, containing the retrieved keys and values.

DataWeave Script:

%dw 2.0

output application/xml

{

users: payload.users.&user

}

Input XML Payload:

<?xml version=’1.0′ encoding=’US-ASCII’?>

<users>

<user>Mariano</user>

<user>Martin</user>

<user>Leandro</user>

<admin>Admin</admin>

<admin>org_owner</admin>

</users>

Output XML:

<?xml version=’1.0′ encoding=’US-ASCII’?>

<users>

<user>Mariano</user>

<user>Martin</user>

<user>Leandro</user>

</users>

Note that unlike the multi-value selector, the output of this selector is an object, where the original keys for each value are also extracted.

Select All the Descendant Key-Value Pairs

This example uses the .. and & selectors in myVar.people..&name to select and return an array that contains all descendant objects from myData input that contain the key name. It also transforms the JSON input to XML output.

DataWeave Script:

%dw 2.0

var myData = {

“people”: {

“person”: {

“name”: “Nial”,

“address”: {

“street”: {

“name”: “Italia”,

“number”: 2164

},

“area”: {

“zone”: “San Isidro”,

“name”: “Martinez”

}

}

}

}

}

output application/xml

names: {(myData.people..&name)}

Output XML:

<?xml version=’1.0′ encoding=’UTF-8′?>

<names>

<name>Nial</name>

<name>Italia</name>

<name>Martinez</name>

</names>

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 days ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago