coderz.py

Keep Coding Keep Cheering!

Range selector (anIndex to anotherIndex)

Range selector (anIndex to anotherIndex)

If you need multiple sequential values from an Array, DataWeave allows you to select a range of values with the range selector ([n to m]). Instead of returning a single value like the index selector does, it will return an Array of values:


Input:

[“prod”, “qa”, “dev”]

DW Script:

%dw 2.0

output json

payload[0 to 1]

Output:

[“prod”, “qa”]


Just like with the index selector, negative indexes can be used to select a range of values starting from the end of the Array.

The to selector returns values of matching indices in an array or string. You can also use it to reverse the order of the indices in the range. The selector treats characters in the string as indices.

  • Selecting an index from an array:

    • [1,2,3,4][0] returns 1


      The index of the first element in an array is always 0.

    • [1,2,3,4][3] returns 4

Range Selector Over an Array

Range selectors limit the output to only the elements specified by the range on that specific order. This selector allows you to slice an array or even invert it.

DataWeave Script:

%dw 2.0

output application/json

{

  slice: [0,1,2][0 to 1],

  last: [0,1,2][-1 to 0]

}

Output JSON:

{

  “slice”: [

    0,

    1

  ],

  “last”: [

    2,

    1,

    0

  ]

}

Range Selector Over a String

The Range selector limits the output to only the elements specified by the range on that specific order, treating the string as an array of characters. This selector enables you to slice a string or invert it.

DataWeave Script:

%dw 2.0

output application/json

{

  slice: “DataWeave”[0 to 1],

  middle : “superfragilisticexpialadocious”[10 to 13],

  last: “DataWeave”[-1 to 0]

}

Output JSON:

{

  “slice”: “Da”,

  “middle”: “list”,

  “last”: “evaeWataD”

}

Follow Me

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

Instagram

Facebook

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement