field()

Returns the value of a field whose name is determined dynamically by an expression.

Syntax

field(EXPR)

Parameters

EXPR
An expression that evaluates to a field name. Required. If the result is null, returns null.

Description

The field() function evaluates EXPR and uses the result as a field name to look up the corresponding value in the current record.

If EXPR evaluates to null, or no field with that name exists in the record, null is returned.

In most cases, writing a field name directly is sufficient and field() is not needed. However, it is useful in the following situations:

  • Referencing a field name that contains spaces or special characters
  • Determining a field name dynamically using a variable or expression

Error codes

Error codeMessageDescription
90670Enter a field name.No argument was passed.

Usage examples

To prepare the WEB_APACHE_SAMPLE table used in these examples, refer to Preparing sample data.

  1. Referencing a field name that contains spaces

    json "[
      {'Registered No.': 1, 'Item': 'Fender Precision Bass'},
      {'Registered No.': 2, 'Item': 'Gibson Jazz'}
    ]"
    | search field("Registered No.") == 2
    | # Returns only records where the 'Registered No.' field equals 2.
    
  2. Querying WEB_APACHE_SAMPLE with a field name specified dynamically via a variable

    set target_field = "method"
    | table limit=5 WEB_APACHE_SAMPLE | eval result = field($("target_field")) | fields method, result
    | # result: the value of the method field
    
  3. Returns null when a nonexistent field name is specified

    json "{'val': 1}" | eval result = field("nonexistent")
    | # result: null
    
  4. Returns null when the expression evaluates to null

    json "{'val': null}" | eval result = field(val)
    | # result: null
    

Compatibility

The field() function has been available since before Sonar 4.0.