nth

Table of Contents

Prototype: nth(list_or_container, position_or_key)

Return type: string

Description: Returns the element of list_or_container at zero-based position_or_key.

If an invalid position (below 0 or above the size of the list minus 1) or missing key is requested, this function does not return a valid value.

list_or_container can be an slist or a data container. If it's a slist, the offset is simply the position in the list. If it's a data container, the meaning of the position_or_key depends on its top-level contents: for a list like [1,2,3,4] you will get the list element at position_or_key. For a key-value map like { a: 100, b: 200 }, a position_or_key of a returns 100.

Arguments:

  • list_or_container: string, in the range: [a-zA-Z0-9_$(){}\[\].:]+
  • position_or_key: string, in the range: .*

Example:

body common control
{
      bundlesequence => { "test" };
}

bundle agent test
{
  vars:
      "test" slist => {
                        1,2,3,
                        "one", "two", "three",
                        "long string",
                        "four", "fix", "six",
                        "one", "two", "three",
      };
      "test_str" string => format("%S", test);

      "test2" data => parsejson("[1, 2, 3, null]");
      "test2_str" string => format("%S", test2);

      "test3" data => parsejson('{ "x": true, "y": "z" }');
      "test3_str" string => format("%S", test3);

      "nth" slist => { 1, 2, 6, 10, 11, 1000 };
      "nth2" slist => getindices(test2);
      "nth3" slist => getindices(test3);

      "access[$(nth)]" string => nth(test, $(nth));
      "access[0]" string => nth(test, 0);

      "access2[$(nth2)]" string => nth(test2, $(nth2));
      "access3[$(nth3)]" string => nth(test3, $(nth3));

  reports:
      "The test list is $(test_str)";
      "element #$(nth) of the test list: $(access[$(nth)])";
      "element #0 of the test list: $(access[0])";

      "The test2 data container is $(test2_str)";
      "element #$(nth2) of the test2 data container: $(access2[$(nth2)])";

      "The test3 data container is $(test3_str)";
      "element #$(nth3) of the test3 data container: $(access3[$(nth3)])";
}

Output:

R: The test list is { "1", "2", "3", "one", "two", "three", "long string", "four", "fix", "six", "one", "two", "three" }
R: element #1 of the test list: 2
R: element #2 of the test list: 3
R: element #6 of the test list: long string
R: element #10 of the test list: one
R: element #11 of the test list: two
R: element #1000 of the test list: $(access[1000])
R: element #0 of the test list: 1
R: The test2 data container is [1,2,3,null]
R: element #0 of the test2 data container: 1
R: element #1 of the test2 data container: 2
R: element #2 of the test2 data container: 3
R: element #3 of the test2 data container: null
R: The test3 data container is {"x":true,"y":"z"}
R: element #x of the test3 data container: true
R: element #y of the test3 data container: z

See also: length().