# JSONata functions

> The built-in functions of JSONata, the language that `data.transform` and the expression fallback of flow nodes use.

Source: https://docs.sommatic.ai/en/expressions/jsonata-functions/

Version: 2.1.0 (MIT). Official documentation: https://docs.jsonata.org/overview

Write JSONata without `{{ }}`; fields of the input are read by name. The signature uses JSONata notation (`s` string, `n` number, `b` boolean, `a` array, `o` object, `f` function, `x` any, `-` the input, `?` optional).

```
$sum(items.price)
```

## Functions

### `$abs  <n-:n>`

Returns the absolute value of a number. If the argument is omitted, the context value is used. Example: `$abs(-5)` returns `5`.

```javascript
$abs(-4.5)
```

Result (number):

```json
4.5
```

### `$append  <xx:a>`

Returns an array with the values of the first argument followed by the values of the second; a value that is not an array is treated as a single-element array. Example: `$append([1,2,3], 4)` returns `[1,2,3,4]`.

```javascript
$append(body.tags, 'priority')
```

Result (list):

```json
[
  "new",
  "web",
  "new",
  "priority"
]
```

### `$assert  <bs?:x>`

Throws an error with `message` when `condition` is false; when it is true, returns nothing (undefined). Example: `$assert($count(items) > 0, "No items")`.

```javascript
$assert($count(body.items) > 0, 'The order has no items')
```

Result (undefined):

```json
undefined
```

### `$average  <a<n>:n>`

Returns the mean of an array of numbers. Throws an error if any item is not a number. Example: `$average([5,1,3,7,4])` returns `4`.

```javascript
$average(body.items.price)
```

Result (number):

```json
13.166666666666666
```

### `$base64decode  <s-:s>`

Decodes a Base64 string into a UTF-8 string. Example: `$base64decode("bXl1c2VyOm15cGFzcw==")` returns `"myuser:mypass"`.

```javascript
$base64decode('U29tbWF0aWM=')
```

Result (string):

```json
"Sommatic"
```

### `$base64encode  <s-:s>`

Encodes a string as Base64, treating each character as one byte; characters outside the 0x00-0xFF range are not supported. Example: `$base64encode("myuser:mypass")` returns `"bXl1c2VyOm15cGFzcw=="`.

```javascript
$base64encode(body.order_id)
```

Result (string):

```json
"b3JkXzEwNDI="
```

### `$boolean  <x-:b>`

Casts a value to a Boolean: empty strings, `0`, `null`, empty arrays and objects, arrays whose members all cast to `false`, and functions become `false`; other values become `true`.

```javascript
$boolean(body.priority)
```

Result (boolean):

```json
false
```

### `$ceil  <n-:n>`

Rounds a number up to the nearest integer greater than or equal to it. Example: `$ceil(5.3)` returns `6`.

```javascript
$ceil(body.items[0].price)
```

Result (number):

```json
11
```

### `$clone  <(oa)-:o>`

Returns a deep copy of an object or array, made by serializing it to JSON and parsing it back. It is not part of the documented function library; the transform operator `| ... | ... |` uses it to copy its input.

```javascript
$clone(body.customer)
```

Result (object):

```json
{
  "name": "Ana Pérez",
  "segment": "gold"
}
```

### `$contains  <s-(sf):b>`

Returns `true` if the string contains `pattern`, which can be a string (matched as contiguous characters) or a regular expression. Example: `$contains("Hello World", /wo/i)` returns `true`.

```javascript
$contains(body.email, '@example.com')
```

Result (boolean):

```json
true
```

### `$count  <a:n>`

Returns the number of items in an array; a value that is not an array counts as one item. Example: `$count([1,2,3,1])` returns `4`.

```javascript
$count(body.items)
```

Result (number):

```json
3
```

### `$decodeUrl  <s-:s>`

Decodes a full URL encoded with `$encodeUrl`, turning percent-escape sequences back into characters.

```javascript
$decodeUrl('https://example.com/a%20b')
```

Result (string):

```json
"https://example.com/a b"
```

### `$decodeUrlComponent  <s-:s>`

Decodes a URL component encoded with `$encodeUrlComponent`. Example: `$decodeUrlComponent("%3Fx%3Dtest")` returns `"?x=test"`.

```javascript
$decodeUrlComponent('Ana%20P%C3%A9rez')
```

Result (string):

```json
"Ana Pérez"
```

### `$distinct  <x:x>`

Returns an array with duplicate values removed, comparing values deeply as the `=` operator does. Example: `$distinct([1,2,3,3,4,3,5])` returns `[1,2,3,4,5]`.

```javascript
$distinct(body.tags)
```

Result (list):

```json
[
  "new",
  "web"
]
```

### `$each  <o-f:a>`

Applies a function to each key/value pair of an object and returns an array with the results; the function receives the value and, optionally, the key. Example: `$each(Address, function($v, $k) { $k & ": " & $v })`.

```javascript
$each(body.customer, function($value, $key) { $key & '=' & $value })
```

Result (list):

```json
[
  "name=Ana Pérez",
  "segment=gold"
]
```

### `$encodeUrl  <s-:s>`

Encodes a full URL by replacing characters that are not valid in a URL with UTF-8 percent-escape sequences, keeping its structural characters such as `/`, `?` and `=`.

```javascript
$encodeUrl('https://example.com/search?q=Ana Pérez')
```

Result (string):

```json
"https://example.com/search?q=Ana%20P%C3%A9rez"
```

### `$encodeUrlComponent  <s-:s>`

Encodes a URL component by replacing reserved and non-ASCII characters with UTF-8 percent-escape sequences. Example: `$encodeUrlComponent("?x=test")` returns `"%3Fx%3Dtest"`.

```javascript
$encodeUrlComponent(body.customer.name)
```

Result (string):

```json
"Ana%20P%C3%A9rez"
```

### `$error  <s?:x>`

Throws an error, with an optional message, which stops the evaluation. Example: `$error("Invalid status")`.

```javascript
$exists(body.shipping) ? body.shipping : $error('Missing shipping')
```

Throws:

```text
Missing shipping
```

### `$eval  <sx?:x>`

Parses and evaluates a string as JSON or as a JSONata expression, using the current context or the optional `context` argument. Example: `$eval("[1,2,3]")` returns `[1,2,3]`.

```javascript
$eval('[1, 2, 3]')
```

Result (list):

```json
[
  1,
  2,
  3
]
```

### `$exists  <x:b>`

Returns `true` if the expression evaluates to a value and `false` if it matches nothing, such as a path to a missing field. Example: `$exists(Account.Email)`.

```javascript
$exists(body.shipping)
```

Result (boolean):

```json
false
```

### `$filter  <af>`

Returns the values of an array for which the function returns `true`; the function receives the value and, optionally, its index and the whole array. Example: `$filter([1,2,3,4], function($v) { $v % 2 = 0 })` returns `[2,4]`.

```javascript
$filter(body.items, function($item) { $item.qty > 0 }).sku
```

Result (list):

```json
[
  "A-100",
  "C-300"
]
```

### `$floor  <n-:n>`

Rounds a number down to the nearest integer less than or equal to it. Example: `$floor(-5.3)` returns `-6`.

```javascript
$floor(body.items[0].price)
```

Result (number):

```json
10
```

### `$formatBase  <n-n?:s>`

Converts a number to a string representing an integer in the given radix, from 2 to 36 (default 10). Example: `$formatBase(100, 2)` returns `"1100100"`.

```javascript
$formatBase(255, 16)
```

Result (string):

```json
"ff"
```

### `$formatInteger  <n-s:s>`

Formats a number as an integer string according to a picture string, following the XPath `fn:format-integer` syntax. Example: `$formatInteger(1999, 'I')` returns `"MCMXCIX"`.

```javascript
$formatInteger(1042, '000000')
```

Result (string):

```json
"001042"
```

### `$formatNumber  <n-so?:s>`

Formats a number as a decimal string according to a picture string, following the XPath `fn:format-number` syntax; the optional `options` object overrides characters such as the decimal separator. Example: `$formatNumber(12345.6, '#,###.00')` returns `"12,345.60"`.

```javascript
$formatNumber(1234.5, '#,##0.00')
```

Result (string):

```json
"1,234.50"
```

### `$fromMillis  <n-s?s?:s>`

Converts milliseconds since the Unix epoch into a timestamp string: ISO 8601 by default, or formatted with an XPath `fn:format-dateTime` picture and an optional `±HHMM` timezone. Example: `$fromMillis(1510067557121, '[M01]/[D01]/[Y0001]')` returns `"11/07/2017"`.

```javascript
$fromMillis(1795703400000)
```

Result (string):

```json
"2026-11-26T14:30:00.000Z"
```

```javascript
$fromMillis(1795703400000, '[Y0001]-[M01]-[D01]')
```

Result (string):

```json
"2026-11-26"
```

### `$join  <a<s>s?:s>`

Joins an array of strings into a single string, with an optional separator (empty by default). Throws an error if any item is not a string. Example: `$join(['a','b','c'], ', ')` returns `"a, b, c"`.

```javascript
$join(body.items.sku, ', ')
```

Result (string):

```json
"A-100, B-200, C-300"
```

### `$keys  <x-:a<s>>`

Returns an array with the keys of an object; for an array of objects, returns the de-duplicated keys of all of them.

```javascript
$keys(body.customer)
```

Result (list):

```json
[
  "name",
  "segment"
]
```

### `$length  <s-:n>`

Returns the number of characters in a string. Throws an error if the argument is not a string. Example: `$length("Hello World")` returns `11`.

```javascript
$length(body.order_id)
```

Result (number):

```json
8
```

### `$lookup  <x-s:x>`

Returns the value stored under `key` in an object; for an array of objects, returns the values of every occurrence of `key`. Example: `$lookup(Address, "City")`.

```javascript
$lookup(body.customer, 'segment')
```

Result (string):

```json
"gold"
```

### `$lowercase  <s-:s>`

Converts all the characters of a string to lowercase. Example: `$lowercase("Hello World")` returns `"hello world"`.

```javascript
$lowercase(body.customer.name)
```

Result (string):

```json
"ana pérez"
```

### `$map  <af>`

Returns an array with the result of applying a function to each value of an array; the function receives the value and, optionally, its index and the whole array. Example: `$map([1..5], $string)` returns `["1","2","3","4","5"]`.

```javascript
$map(body.items, function($item) { $item.qty * $item.price })
```

Result (list):

```json
[
  21,
  0,
  25
]
```

### `$match  <s-f<s:o>n?:a<o>>`

Applies a regular expression to a string and returns an array of objects, one per match, with the fields `match`, `index` and `groups`; the optional `limit` caps the number of matches. Example: `$match("ababbabbcc", /a(b+)/)`.

```javascript
$match(body.order_id, /\d+/).match
```

Result (string):

```json
"1042"
```

### `$max  <a<n>:n>`

Returns the largest number in an array of numbers. Throws an error if any item is not a number. Example: `$max([5,1,3,7,4])` returns `7`.

```javascript
$max(body.items.price)
```

Result (number):

```json
25
```

### `$merge  <a<o>:o>`

Merges an array of objects into a single object; when keys repeat, the value from the last object wins. Example: `$merge([{"a":1},{"a":2,"b":3}])` returns `{"a":2,"b":3}`.

```javascript
$merge([body.customer, { 'vip': true }])
```

Result (object):

```json
{
  "name": "Ana Pérez",
  "segment": "gold",
  "vip": true
}
```

### `$min  <a<n>:n>`

Returns the smallest number in an array of numbers. Throws an error if any item is not a number. Example: `$min([5,1,3,7,4])` returns `1`.

```javascript
$min(body.items.qty)
```

Result (number):

```json
0
```

### `$not  <x-:b>`

Casts the argument to a Boolean with the rules of `$boolean` and returns its negation. Example: `$not(0)` returns `true`.

```javascript
$not($exists(body.shipping))
```

Result (boolean):

```json
true
```

### `$number  <(nsb)-:n>`

Casts a value to a number: numbers pass unchanged, strings holding a valid JSON number (or a `0x`, `0o` or `0b` literal) are parsed, `true` becomes `1` and `false` becomes `0`; any other value throws an error. Example: `$number("5")` returns `5`.

```javascript
$number('42.5')
```

Result (number):

```json
42.5
```

### `$pad  <s-ns?:s>`

Pads a string to at least `|width|` characters with `char` (a space by default): a positive width pads on the right, a negative width on the left. Example: `$pad("foo", -5, "#")` returns `"##foo"`.

```javascript
$pad(body.order_id, 12, '*')
```

Result (string):

```json
"ord_1042****"
```

### `$parseInteger  <s-s:n>`

Parses a string into an integer using a picture string with the same syntax as `$formatInteger`. Example: `$parseInteger('12,345,678', '#,##0')` returns `12345678`.

```javascript
$parseInteger('001,042', '#,##0')
```

Result (number):

```json
1042
```

### `$power  <n-n:n>`

Returns `base` raised to the power of `exponent`. Throws an error if the result cannot be represented as a JSON number. Example: `$power(2, -2)` returns `0.25`.

```javascript
$power(2, 10)
```

Result (number):

```json
1024
```

### `$random  <:n>`

Returns a pseudo-random number greater than or equal to 0 and less than 1.

```javascript
$random()
```

Result (number) · Random: a new value on every run:

```json
0.5850853985132143
```

### `$reduce  <afj?:j>`

Combines the values of an array into one by applying a function successively; the function receives the accumulator and the current value, and the optional `init` sets the starting value (by default, the first item). Example: `$reduce([1..5], function($acc, $v) { $acc * $v })` returns `120`.

```javascript
$reduce(body.items.qty, function($sum, $qty) { $sum + $qty }, 0)
```

Result (number):

```json
3
```

### `$replace  <s-(sf)(sf)n?:s>`

Replaces the occurrences of `pattern` (a string or a regular expression) in a string with `replacement`, which can be a string (with `$1`, `$2`... for captured groups) or a function; the optional `limit` caps the number of replacements. Example: `$replace("John Smith and John Jones", "John", "Mr", 1)` returns `"Mr Smith and John Jones"`.

```javascript
$replace(body.email, '@example.com', '')
```

Result (string):

```json
"ana.perez"
```

### `$reverse  <a:a>`

Returns an array with its values in reverse order. Example: `$reverse(["Hello", "World"])` returns `["World", "Hello"]`.

```javascript
$reverse(body.items.sku)
```

Result (list):

```json
[
  "C-300",
  "B-200",
  "A-100"
]
```

### `$round  <n-n?:n>`

Rounds a number to the given number of decimal places (0 by default; a negative value rounds to the left of the decimal point), using round half to even. Example: `$round(123.456, 2)` returns `123.46`.

```javascript
$round(10.567, 2)
```

Result (number):

```json
10.57
```

### `$shuffle  <a:a>`

Returns an array with its values in random order. Example: `$shuffle([1..9])`.

```javascript
$shuffle(body.items.sku)
```

Result (list) · Random: a new value on every run:

```json
[
  "A-100",
  "C-300",
  "B-200"
]
```

### `$sift  <o-f?:o>`

Returns an object with only the key/value pairs for which the function returns `true`; the function receives the value and, optionally, the key and the whole object. Example: `$sift(Product, function($v, $k) { $k ~> /^Product/ })`.

```javascript
$sift(body.customer, function($value) { $value != 'gold' })
```

Result (object):

```json
{
  "name": "Ana Pérez"
}
```

### `$single  <af?>`

Returns the only value of an array that satisfies the function (or the only value, if no function is given). Throws an error if the number of matching values is not exactly one. Example: `$single(Product, function($v) { $v.SKU = "0406654608" })`.

```javascript
$single(body.items, function($item) { $item.sku = 'C-300' }).price
```

Result (number):

```json
25
```

### `$sort  <af?:a>`

Returns a sorted array: numbers in increasing order and strings by Unicode code point, or in the order set by an optional comparator `function($l, $r)` that returns `true` when `$l` must go after `$r`. The sort is stable. Example: `$sort(Product, function($l, $r) { $l.Price > $r.Price })`.

```javascript
$sort(body.items, function($left, $right) { $left.price > $right.price }).sku
```

Result (list):

```json
[
  "B-200",
  "A-100",
  "C-300"
]
```

### `$split  <s-(sf)n?:a<s>>`

Splits a string into an array of substrings using a string or regular expression separator; the optional `limit` caps the number of substrings returned. Example: `$split("so many words", " ", 2)` returns `["so", "many"]`.

```javascript
$split(body.email, '@')
```

Result (list):

```json
[
  "ana.perez",
  "example.com"
]
```

### `$spread  <x-:a<o>>`

Splits an object into an array of objects with one key/value pair each; for an array of objects, it does so for all of them. Example: `$spread({"a":1,"b":2})` returns `[{"a":1},{"b":2}]`.

```javascript
$spread(body.customer)
```

Result (list):

```json
[
  {
    "name": "Ana Pérez"
  },
  {
    "segment": "gold"
  }
]
```

### `$sqrt  <n-:n>`

Returns the square root of a number. Throws an error if the number is negative. Example: `$sqrt(4)` returns `2`.

```javascript
$sqrt(16)
```

Result (number):

```json
4
```

### `$string  <x-b?:s>`

Casts a value to a string: strings pass unchanged, functions become an empty string, and other values are serialized as JSON (pretty-printed if `prettify` is `true`). Infinity and NaN throw an error. Example: `$string(5)` returns `"5"`.

```javascript
$string(body.items[0])
```

Result (string):

```json
"{\"sku\":\"A-100\",\"qty\":2,\"price\":10.5}"
```

### `$substring  <s-nn?:s>`

Returns the part of a string that starts at the zero-based position `start` (negative values count from the end), with at most `length` characters when given. Example: `$substring("Hello World", 3, 5)` returns `"lo Wo"`.

```javascript
$substring(body.order_id, 4)
```

Result (string):

```json
"1042"
```

### `$substringAfter  <s-s:s>`

Returns the part of a string after the first occurrence of `chars`, or the whole string if `chars` does not occur. Example: `$substringAfter("Hello World", " ")` returns `"World"`.

```javascript
$substringAfter(body.email, '@')
```

Result (string):

```json
"example.com"
```

### `$substringBefore  <s-s:s>`

Returns the part of a string before the first occurrence of `chars`, or the whole string if `chars` does not occur. Example: `$substringBefore("Hello World", " ")` returns `"Hello"`.

```javascript
$substringBefore(body.email, '@')
```

Result (string):

```json
"ana.perez"
```

### `$sum  <a<n>:n>`

Returns the sum of an array of numbers. Throws an error if any item is not a number. Example: `$sum([5,1,3,7,4])` returns `20`.

```javascript
$sum(body.items.(qty * price))
```

Result (number):

```json
46
```

### `$toMillis  <s-s?:n>`

Converts a timestamp string into milliseconds since the Unix epoch. Without a picture the input must be ISO 8601; with one it is parsed using the XPath `fn:format-dateTime` syntax. Example: `$toMillis("2017-11-07T15:07:54.972Z")` returns `1510067274972`.

```javascript
$toMillis(body.created_at)
```

Result (number):

```json
1795598100000
```

### `$trim  <s-:s>`

Normalizes the whitespace of a string: replaces tabs, carriage returns and line feeds with spaces, collapses consecutive spaces into one, and removes leading and trailing spaces. Example: `$trim(" Hello \n World ")` returns `"Hello World"`.

```javascript
$trim('  Ana   Pérez  ')
```

Result (string):

```json
"Ana Pérez"
```

### `$type  <x:s>`

Returns the type of a value as a string: `null`, `number`, `string`, `boolean`, `array`, `object` or `function`; for an undefined value it returns undefined.

```javascript
$type(body.items)
```

Result (string):

```json
"array"
```

### `$uppercase  <s-:s>`

Converts all the characters of a string to uppercase. Example: `$uppercase("Hello World")` returns `"HELLO WORLD"`.

```javascript
$uppercase(body.order_id)
```

Result (string):

```json
"ORD_1042"
```

### `$zip  <a+>`

Combines several arrays into an array of arrays grouped by position; the result is as long as the shortest input. Example: `$zip([1,2,3], [4,5], [7,8,9])` returns `[[1,4,7],[2,5,8]]`.

```javascript
$zip(body.items.sku, body.items.qty)
```

Result (list):

```json
[
  [
    "A-100",
    2
  ],
  [
    "B-200",
    0
  ],
  [
    "C-300",
    1
  ]
]
```
