asInt method

Expr<int?> asInt()

Extract the value as unquoted text and cast it to an integer.

This method performs a two-step conversion:

  1. The value is extracted as its unquoted text representation (e.g. ->>).
  2. The resulting text is cast to an integer using standard SQL casting rules.

In SQL this is conceptually similar to:

CAST(JSON_VALUE(this, '$') AS BIGINT)

Extraction Behavior:

  • JSON Number 42 becomes text "42".
  • JSON Number 3.14 becomes text "3.14".
  • JSON String "123" becomes text "123".
  • JSON String "hello" becomes text "hello".
  • JSON Boolean true becomes text "true" (or "1" on SQLite)..
  • JSON Object/Array becomes the JSON string representation (e.g. '{"a":1}').
  • JSON Null null becomes SQL NULL.

Casting Behavior:

  • PostgreSQL: Throws a runtime exception if the text is not a valid integer.
  • SQLite: Parses the integer prefix of the string (e.g. "12abc" becomes 12). Returns 0 if no valid prefix exists.

Warning

This is unsafe and may cause runtime errors.

If the JSON data does not match your expectations, the cast may cause runtime failures or silently return unexpected values (like 0).

Implementation

Expr<int?> asInt() =>
    CastExpression._(ExpressionJsonExtract._(this), ColumnType.integer);