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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago