On this page
Sommatic Docs
Open portal

JSONata functions

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

View as Markdown
Open in

Version 2.1.0 MIT Official documentation

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.

$abs(-4.5)
Result number
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].

$append(body.tags, 'priority')
Result list
["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").

$assert($count(body.items) > 0, 'The order has no items')
Result undefined
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.

$average(body.items.price)
Result number
13.166666666666666

$base64decode <s-:s>

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

$base64decode('U29tbWF0aWM=')
Result string
"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==".

$base64encode(body.order_id)
Result string
"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.

$boolean(body.priority)
Result boolean
false

$ceil <n-:n>

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

$ceil(body.items[0].price)
Result number
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.

$clone(body.customer)
Result object
{"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.

$contains(body.email, '@example.com')
Result boolean
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.

$count(body.items)
Result number
3

$decodeUrl <s-:s>

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

$decodeUrl('https://example.com/a%20b')
Result string
"https://example.com/a b"

$decodeUrlComponent <s-:s>

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

$decodeUrlComponent('Ana%20P%C3%A9rez')
Result string
"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].

$distinct(body.tags)
Result list
["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 }).

$each(body.customer, function($value, $key) { $key & '=' & $value })
Result list
["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 =.

$encodeUrl('https://example.com/search?q=Ana Pérez')
Result string
"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".

$encodeUrlComponent(body.customer.name)
Result string
"Ana%20P%C3%A9rez"

$error <s?:x>

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

$exists(body.shipping) ? body.shipping : $error('Missing shipping')
Throws
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].

$eval('[1, 2, 3]')
Result list
[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).

$exists(body.shipping)
Result boolean
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].

$filter(body.items, function($item) { $item.qty > 0 }).sku
Result list
["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.

$floor(body.items[0].price)
Result number
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".

$formatBase(255, 16)
Result string
"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".

$formatInteger(1042, '000000')
Result string
"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".

$formatNumber(1234.5, '#,##0.00')
Result string
"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".

$fromMillis(1795703400000)
Result string
"2026-11-26T14:30:00.000Z"
$fromMillis(1795703400000, '[Y0001]-[M01]-[D01]')
Result string
"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".

$join(body.items.sku, ', ')
Result string
"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.

$keys(body.customer)
Result list
["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.

$length(body.order_id)
Result number
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").

$lookup(body.customer, 'segment')
Result string
"gold"

$lowercase <s-:s>

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

$lowercase(body.customer.name)
Result string
"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"].

$map(body.items, function($item) { $item.qty * $item.price })
Result list
[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+)/).

$match(body.order_id, /\d+/).match
Result string
"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.

$max(body.items.price)
Result number
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}.

$merge([body.customer, { 'vip': true }])
Result object
{"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.

$min(body.items.qty)
Result number
0

$not <x-:b>

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

$not($exists(body.shipping))
Result boolean
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.

$number('42.5')
Result number
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".

$pad(body.order_id, 12, '*')
Result string
"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.

$parseInteger('001,042', '#,##0')
Result number
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.

$power(2, 10)
Result number
1024

$random <:n>

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

$random()
Result number Random: a new value on every run
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.

$reduce(body.items.qty, function($sum, $qty) { $sum + $qty }, 0)
Result number
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".

$replace(body.email, '@example.com', '')
Result string
"ana.perez"

$reverse <a:a>

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

$reverse(body.items.sku)
Result list
["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.

$round(10.567, 2)
Result number
10.57

$shuffle <a:a>

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

$shuffle(body.items.sku)
Result list Random: a new value on every run
["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/ }).

$sift(body.customer, function($value) { $value != 'gold' })
Result object
{"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" }).

$single(body.items, function($item) { $item.sku = 'C-300' }).price
Result number
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 }).

$sort(body.items, function($left, $right) { $left.price > $right.price }).sku
Result list
["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"].

$split(body.email, '@')
Result list
["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}].

$spread(body.customer)
Result list
[{"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.

$sqrt(16)
Result number
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".

$string(body.items[0])
Result string
"{\"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".

$substring(body.order_id, 4)
Result string
"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".

$substringAfter(body.email, '@')
Result string
"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".

$substringBefore(body.email, '@')
Result string
"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.

$sum(body.items.(qty * price))
Result number
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.

$toMillis(body.created_at)
Result number
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".

$trim('  Ana   Pérez  ')
Result string
"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.

$type(body.items)
Result string
"array"

$uppercase <s-:s>

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

$uppercase(body.order_id)
Result string
"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]].

$zip(body.items.sku, body.items.qty)
Result list
[["A-100",2],["B-200",0],["C-300",1]]

Install agent tools

Give your coding agent the official Sommatic AI docs: skills, the docs MCP server and Markdown pages, so it never has to scrape the site.

Skills only. They do not update by themselves; run it again to refresh.

npx skills add https://docs.sommatic.ai
How agents read these docs