valueof()

Returns the value at a specified key or index position from a map or array.

Syntax

valueof(COMPOUND, KEY)

Parameters

COMPOUND
The map or array from which to extract a value.
KEY
A key string for maps, or an integer index for arrays.

Description

The valueof() function extracts and returns the value at a specific position from a compound object.

  • If COMPOUND is a map: returns the value associated with KEY.
  • If COMPOUND is an array: uses KEY as an integer index and returns the element at that position. Indices start at 0.

The function returns null in the following situations:

  • COMPOUND or KEY is null
  • COMPOUND is neither a map nor an array
  • A string key is specified for an array
  • An integer index is specified for a map (when the map's key type is not integer)
  • The index is out of the valid range of the array

Error codes

N/A

Usage examples

  1. Extract a value from an array by index (indices start at 0)

    json "{}"
    | eval foods = array("Apple", "Banana", "Cucumber")
    | eval food = valueof(foods, 2)
    | # food: Cucumber
    
  2. Extract a value from a map by key

    json "{}"
    | eval foods = dict("a", "Apple", "b", "Banana", "c", "Cucumber")
    | eval food = valueof(foods, "b")
    | # food: Banana
    
  3. COMPOUND is null

    json "{}" | eval food = valueof(null, "b")
    | # food: null
    
  4. Array index is out of the valid range

    json "{}"
    | eval foods = array("Apple", "Banana")
    | eval food = valueof(foods, 5)
    | # food: null
    

Compatibility

valueof() has been available since before Sonar 4.0.