### JSONata Built-in Function Signatures Examples Source: https://docs.jsonata.org/embedding-extending Illustrates the signatures of common JSONata built-in functions. ```JSONata $count has signature ; it accepts an array and returns a number. ``` ```JSONata $append has signature ; it accepts two arrays and returns an array. ``` ```JSONata $sum has signature :n>; it accepts an array of numbers and returns a number. ``` ```JSONata $reduce has signature :j>; it accepts a reducer function f and an a (array of JSON objects) and returns a JSON object. ``` -------------------------------- ### Install JSONata via NPM Source: https://docs.jsonata.org/using-nodejs Use this command to add the JSONata library to your Node.js project dependencies. ```bash npm install jsonata ``` -------------------------------- ### JSONata Infinite Loop Example Source: https://docs.jsonata.org/guardrails Demonstrates a tail-recursive function in JSONata that would run indefinitely without a timeout guardrail. ```jsonata ( $inf := function() { $inf() }; $inf() ) ``` -------------------------------- ### Convert Date Formats using $toMillis() and $fromMillis() Source: https://docs.jsonata.org/date-time Convert dates between different formats using $toMillis() for parsing and $fromMillis() for formatting. This example shows converting US/European date formats and then reformatting. ```JSONata $toMillis('10/12/2018', '[D]/[M]/[Y]') ~> $fromMillis('[M]/[D]/[Y]') ``` ```JSONata $toMillis('10/12/2018', '[D]/[M]/[Y]') ~> $fromMillis('[FNn], [D1o] [MNn] [YI]') ``` -------------------------------- ### Higher-order function example Source: https://docs.jsonata.org/programming Illustrates the concept of higher-order functions in JSONata. The `$twice` function takes another function as an argument and returns a new function, demonstrating functional composition. ```JSONata ( $twice := function($f) { function($x){ $f($f($x)) } }; $add3 := function($y){ $y + 3 }; $add6 := $twice($add3); $add6(7) ) ``` -------------------------------- ### JSONata Syntax Error Example Source: https://docs.jsonata.org/embedding-extending Illustrates the structure of an error object when a JSONata expression contains a syntax error. ```json { "code": "S0202", "stack": "...", "position": 16, "token": "}", "value": "]", "message": "Syntax error: expected ']' got '}'" } ``` -------------------------------- ### Defining and Using a Regex Matcher Function Source: https://docs.jsonata.org/regex Shows how to define a regex as a function and bind it to a variable, then invoke this function on a string to get match details. The generated function returns an object with match information. ```JSONata $matcher := /[a-z]*an[a-z]*/i $matcher('A man, a plan, a canal, Panama!') ``` -------------------------------- ### Evaluate JSONata Expression in Node.js Source: https://docs.jsonata.org/using-nodejs This example demonstrates how to load JSONata, define data, create an expression, and evaluate it asynchronously within a Node.js application. The expression calculates the sum of values from an array. ```javascript const jsonata = require('jsonata'); const data = { example: [ {value: 4}, {value: 7}, {value: 13} ] }; (async () => { const expression = jsonata('$sum(example.value)'); const result = await expression.evaluate(data); // returns 24 })() ``` -------------------------------- ### Chained Partial Application: Get First N Characters Source: https://docs.jsonata.org/programming Demonstrates further partial application where a partially applied function is itself partially applied. Here, $firstN is applied with a placeholder for the string, and then $first5 is created by specifying the length. ```JSONata ( $firstN := $substring(?, 0, ?); $first5 := $firstN(?, 5); $first5("Hello, World") ) ``` -------------------------------- ### Get Current Timestamp with $now() Source: https://docs.jsonata.org/date-time Use $now() to get the current timestamp as an ISO 8601 formatted string. The timestamp is captured once at the start of expression evaluation and remains consistent throughout. ```JSONata { "invoiceTime": $now(), "total": $sum(Account.Order.Product.(Price * Quantity)), "closingTime": $now() } ``` -------------------------------- ### Getting Subsequent Matches with next() Source: https://docs.jsonata.org/regex Demonstrates how to use the 'next' function returned by a regex match to find subsequent occurrences of the pattern within the string. ```JSON { "match": "canal", "start": 17, "end": 22, "groups": [], "next": "#0" } ``` -------------------------------- ### Extract Substring with $substring() Source: https://docs.jsonata.org/string-functions Use $substring() to extract a portion of a string. Specify the starting position and an optional length. Negative start indices count from the end of the string. ```jsonata $substring("Hello World", 3) ``` ```jsonata $substring("Hello World", 3, 5) ``` ```jsonata $substring("Hello World", -4) ``` ```jsonata $substring("Hello World", -4, 2) ``` -------------------------------- ### Partial Application: Get First 5 Characters Source: https://docs.jsonata.org/programming Create a function to extract the first five characters of a string using partial application of the $substring function. The '?' acts as a placeholder for the string argument. ```JSONata ( $first5 := $substring(?, 0, 5); $first5("Hello, World") ) ``` -------------------------------- ### JSONata Ackermann Function Example Source: https://docs.jsonata.org/guardrails Illustrates a recursive function in JSONata. While theoretically computable, large inputs can hit stack guardrails. ```jsonata ( $ack := function($m, $n) { $m = 0 ? $n + 1 : $n = 0 ? $ack($m - 1, 1) : $ack($m - 1, $ack($m, $n - 1)) }; $ack(3, 4) ) ``` -------------------------------- ### JSONata Runtime Error Example Source: https://docs.jsonata.org/embedding-extending Illustrates the structure of an error object when a JSONata expression encounters a runtime error during evaluation. ```json { "code": "T1006", "stack": "...", "position": 14, "token": "notafunction", "message": "Attempted to invoke a non-function" } ``` -------------------------------- ### Using SafeRegExp with redos-detector Source: https://docs.jsonata.org/guardrails This snippet shows how to configure JSONata to use a custom RegExp class that wraps the 'redos-detector' library. This helps prevent ReDoS vulnerabilities by checking regex safety before execution. Ensure 'redos-detector' is installed. ```javascript const jsonata = require('jsonata'); const redos = require('redos-detector'); // Simple wrapper that invokes redos-detector before delegating // to built-in RegExp class const SafeRegExp = function(regex) { if (!redos.isSafe(regex).safe) { throw { code: 'U1001', stack: (new Error()).stack, value: regex, message: 'Rejecting regex (potential ReDoS): ' + regex }; } this.regex = regex; }; SafeRegExp.prototype.exec = function(str) { return this.regex.exec(str); } const data = {JSON: data}; const options = { RegexEngine: SafeRegExp }; (async () => { const expression = jsonata('', options); const result = await expression.evaluate(data); })() ``` -------------------------------- ### Closure example with lexical scoping Source: https://docs.jsonata.org/programming Demonstrates closures in JSONata, where a function retains access to its defining environment. The `$AccName` function accesses the `Account` context item from its definition scope, even when invoked in a different context. ```JSONata Account.( $AccName := function() { $.'Account Name' }; Order[OrderID = 'order104'].Product.{ 'Account': $AccName(), 'SKU-' & $string(ProductID): $.'Product Name' } ) ``` -------------------------------- ### Calculate Total Price of Products in Orders Source: https://docs.jsonata.org/sorting-grouping Use the $sum function to calculate the total price of all products across all orders. This is useful for getting a grand total. ```JSONata $sum(Account.Order.Product.Price) ``` -------------------------------- ### JSONata 'and' Operator Example Source: https://docs.jsonata.org/boolean-operators Use the 'and' operator to check if both conditions are true. Operands are cast to boolean if they are not already. ```jsonata library.books["Aho" in authors and price < 50].title ``` -------------------------------- ### Construct Single Object from Multiple Values Source: https://docs.jsonata.org/construction When the object constructor does not immediately follow a dot operator, it aggregates all context values into a single object. This example shows how duplicate keys result in an array of values. ```JSONata Phone{type: number} ``` -------------------------------- ### Y-Combinator for Recursive Anonymous Functions Source: https://docs.jsonata.org/programming An advanced example implementing the Y-combinator to define and apply a recursive anonymous function for calculating the Fibonacci sequence. This avoids explicit function naming for recursion. ```JSONata ( $Y := λ($f) { λ($x) { $x($x) }( λ($g) { $f( (λ($a) {$g($g)($a)}))})}; [1,2,3,4,5,6,7,8,9] . $Y(λ($f) { λ($n) { $n <= 1 ? $n : $f($n-1) + $f($n-2) } }) ($) ) ``` -------------------------------- ### Get String Length with $length() Source: https://docs.jsonata.org/string-functions Use $length() to determine the number of characters in a string. The function expects a string argument; otherwise, an error is thrown. ```jsonata $length("Hello World") ``` -------------------------------- ### $each() Source: https://docs.jsonata.org/object-functions Returns an array containing the values return by the function when applied to each key/value pair in the object. The function parameter will get invoked with two arguments: function(value, name) where the value parameter is the value of each name/value pair in the object and name is its name. The name parameter is optional. ```APIDOC ## $each() ### Description Returns an array containing the values return by the `function` when applied to each key/value pair in the `object`. The `function` parameter will get invoked with two arguments: `function(value, name)` where the `value` parameter is the value of each name/value pair in the object and `name` is its name. The `name` parameter is optional. ### Signature `$each(object, function)` ### Example `$each(Address, function($v, $k) {$k & ": " & $v})` => ``` [ "Street: Hursley Park", "City: Winchester", "Postcode: SO21 2JN" ] ``` ``` -------------------------------- ### JSONata 'or' Operator Example Source: https://docs.jsonata.org/boolean-operators Use the 'or' operator to check if at least one condition is true. Operands are cast to boolean if they are not already. ```jsonata library.books[price < 10 or section="diy"].title ``` -------------------------------- ### Named Recursive Function for Fibonacci Source: https://docs.jsonata.org/programming A more conventional approach to calculating the Fibonacci sequence using a named recursive function $fib. This is presented as a more readable alternative to the Y-combinator example. ```JSONata ( $fib := λ($n) { $n <= 1 ? $n : $fib($n-1) + $fib($n-2) }; [1,2,3,4,5,6,7,8,9] . $fib($) ) ``` -------------------------------- ### Get substring before a character sequence Source: https://docs.jsonata.org/string-functions Returns the substring before the first occurrence of the specified character sequence. If the sequence is not found, the original string is returned. ```JSONata $substringBefore("Hello World", " ") ``` -------------------------------- ### Get Single Matching Element with $single() Source: https://docs.jsonata.org/higher-order-functions Use $single to retrieve a unique element from an array that satisfies a given condition. Ensure that exactly one element matches, otherwise an exception is thrown. ```jsonata $single(Account.Order.Product, function($v, $i, $a) { $v.SKU = "0406654608" }) ``` -------------------------------- ### Handle Non-existent Path Source: https://docs.jsonata.org/simple Attempts to select the 'Nothing' field, which does not exist. Returns undefined. ```JSONata Other.Nothing ``` -------------------------------- ### JSONata Excessive Sequence Example Source: https://docs.jsonata.org/guardrails An example JSONata expression that attempts to generate a sequence of 100 million numbers, which would be prevented by the sequence guardrail. ```jsonata [1..10000].([1..10000]) ``` -------------------------------- ### Chaining Partial Applications: Capitalize First 5 Chars Source: https://docs.jsonata.org/programming Creates a new function $first5Capitalized by chaining a partially applied $substring function with a partially applied $uppercase function. This demonstrates combining partial application and chaining. ```JSONata ( $first5Capitalized := $substring(?, 0, 5) ~> $uppercase(?); $first5Capitalized(Address.City) ) ``` -------------------------------- ### Get keys from an array of objects in JSONata Source: https://docs.jsonata.org/object-functions Returns a de-duplicated list of all keys present in an array of objects. ```jsonata $keys([{"a": 1, "b": 2}, {"b": 3, "c": 4}]) ``` -------------------------------- ### $sift() Source: https://docs.jsonata.org/object-functions See definition under 'Higher-order functions'. ```APIDOC ## $sift() ### Description See definition under 'Higher-order functions'. ### Signature `$sift(object, function)` ``` -------------------------------- ### Factorial using standard recursion Source: https://docs.jsonata.org/programming Demonstrates the classic recursive implementation of the factorial function. This version can lead to stack overflow for large inputs due to its reliance on the call stack for intermediate results. ```JSONata ( $factorial := function($x) { $x <= 1 ? 1 : $x * $factorial($x-1) }; $factorial(170) ) ``` -------------------------------- ### Get distinct array values Source: https://docs.jsonata.org/array-functions Returns an array with duplicate values removed, using deep equality for comparison. ```jsonata $distinct([1,2,3,3,4,3,5]) ``` ```jsonata $distinct(Account.Order.Product.Description.Colour) ``` -------------------------------- ### Join array elements with a separator and limit split Source: https://docs.jsonata.org/string-functions Demonstrates chaining $split() with a limit and $join() to create a formatted string from a subset of split substrings. ```jsonata $split("too much, punctuation. hard; to read", /[ ,.;]+/, 3) ~> $join(', ') ``` -------------------------------- ### Get Absolute Value with $abs() Source: https://docs.jsonata.org/numeric-functions The $abs() function returns the absolute value of a number. If the input is negative, it returns its positive counterpart. ```jsonata $abs(5) ``` ```jsonata $abs(-5) ``` -------------------------------- ### Calculate Power with $power() Source: https://docs.jsonata.org/numeric-functions Use $power() to raise a base number to an exponent. The context value is used as the base if only the exponent is provided. Throws an error for non-representable JSON numbers. ```jsonata $power(2, 8) => 256 $power(2, 0.5) => 1.414213562373 $power(2, -2) => 0.25 ``` -------------------------------- ### Get Current UTC Timestamp Source: https://docs.jsonata.org/date-time-functions Generates a UTC timestamp in ISO 8601 format. All calls within an expression return the same value. ```jsonata $now() ``` -------------------------------- ### JSONata Function Signature Type Options Source: https://docs.jsonata.org/embedding-extending Demonstrates options for function arguments in JSONata signatures. ```JSONata + - one or more arguments of this type * E.g. $zip has signature ; it accepts one array, or two arrays, or three arrays, or... ? - optional argument * E.g. $join has signature s?:s>; it accepts an array of strings and an optional joiner string which defaults to the empty string. It returns a string. - - if this argument is missing, use the context value ("focus"). * E.g. $length has signature ; it can be called as $length(OrderID) (one argument) but equivalently as OrderID.$length(). ``` -------------------------------- ### Filter and Order by Date, then Select Name Source: https://docs.jsonata.org/path-operators Selects names of full-time students, sorted by their date of birth (ISO 8601 format). ```jsonata student[type='fulltime']^(DoB).name ``` -------------------------------- ### Get substring after a character sequence Source: https://docs.jsonata.org/string-functions Returns the substring after the first occurrence of the specified character sequence. If the sequence is not found, the original string is returned. ```JSONata $substringAfter("Hello World", " ") ``` -------------------------------- ### Format Integer to Words Source: https://docs.jsonata.org/numeric-functions Casts a number to a string and formats it as words using the 'w' picture string. This behavior is consistent with fn:format-integer. ```JSONata $formatInteger(2789, 'w') ``` -------------------------------- ### Bind and Use a Variable Source: https://docs.jsonata.org/programming Demonstrates binding a value to a variable and then using that variable in a calculation. The scope of the variable is limited to the block in which it was bound. ```JSONata ( Invoice.( $p := Product.Price; $q := Product.Quantity; $p * $q ) ) ``` -------------------------------- ### Select mobile phone number Source: https://docs.jsonata.org/predicate Extracts the 'number' field from 'Phone' items that are of type 'mobile'. Use this to get the specific number for mobile phones. ```JSONata Phone[type='mobile'].number ``` -------------------------------- ### Group product sales by name with individual price/quantity objects Source: https://docs.jsonata.org/sorting-grouping Explicitly uses $.{...} to create an object for each product within a group, preserving individual price and quantity pairings. Useful when the relationship between price and quantity for each item is important. ```JSONata Account.Order.Product { `Product Name`: $.{ "Price": Price, "Qty": Quantity } } ``` -------------------------------- ### Get keys from an object in JSONata Source: https://docs.jsonata.org/object-functions Returns an array of keys from a given object. If an array of objects is provided, it returns a de-duplicated list of all keys across all objects. ```jsonata $keys({"a": 1, "b": 2}) ``` -------------------------------- ### Group product sales by name with prices and quantities Source: https://docs.jsonata.org/sorting-grouping Groups product sales by 'Product Name' and creates nested objects for 'Price' and 'Qty'. Prices and quantities for the same product name are collected into separate arrays. ```JSONata Account.Order.Product { `Product Name`: { "Price": Price, "Qty": Quantity } } ``` -------------------------------- ### Get Milliseconds Since Epoch Source: https://docs.jsonata.org/date-time-functions Returns the number of milliseconds since the Unix Epoch (January 1, 1970 UTC). All calls within an expression return the same value. ```jsonata $millis() ``` -------------------------------- ### Select all fields of Address Source: https://docs.jsonata.org/predicate Uses the wildcard '*' to select the values of all fields within the 'Address' object. This is helpful for retrieving all address components at once. ```JSONata Address.* ``` -------------------------------- ### Define and use a chained function Source: https://docs.jsonata.org/other-operators Define a new function by chaining existing functions and then use it. ```jsonata ( $uppertrim := $trim ~> $uppercase; $uppertrim(" Hello World ") ) ``` -------------------------------- ### Select First Element from Top-Level Array Source: https://docs.jsonata.org/simple Use the context reference '$' followed by array indexing to select the first object from a top-level array. This is useful when the input is an array and you need to access its elements. ```JSONata $[0] ``` -------------------------------- ### Filter Array Based on String Content Source: https://docs.jsonata.org/string-functions Filters an array of objects, selecting those where the 'number' field starts with '077'. This uses $contains with a regex for pattern matching within an array context. ```jsonata Phone[$contains(number, /^077/)] ``` -------------------------------- ### Define and Invoke an Anonymous Function Source: https://docs.jsonata.org/programming Illustrates defining an anonymous function for calculating volume and then immediately invoking it with specific arguments. ```JSONata function($l, $w, $h){ $l * $w * $h }(10, 10, 5) ``` -------------------------------- ### Construct Array of Objects from Multiple Values Source: https://docs.jsonata.org/construction Use the object constructor immediately following a dot operator to create an array of objects, where each object corresponds to a context value. ```JSONata Phone.{type: number} ``` -------------------------------- ### $sqrt(number) Source: https://docs.jsonata.org/numeric-functions Calculates the square root of a given number. If the number is not provided, it uses the context value. Throws an error for negative numbers. ```APIDOC ## $sqrt(number) ### Description Returns the square root of the value of the `number` parameter. If `number` is not specified, the context value is used. An error is thrown if the value of `number` is negative. ### Signature `$sqrt(number)` ### Parameters #### Path Parameters - **number** (number) - Required - The number to calculate the square root of. If not provided, the context value is used. ### Examples * `$sqrt(4)` => `2` * `$sqrt(2)` => `1.414213562373 ``` -------------------------------- ### Invoke Built-in Functions Source: https://docs.jsonata.org/programming Shows how to invoke built-in JSONata functions like $uppercase, $substring, and $sum with their respective arguments. ```JSONata $uppercase("Hello") ``` ```JSONata $substring("hello world", 0, 5) ``` ```JSONata $sum([1,2,3]) ``` -------------------------------- ### Evaluate with Overridden Bindings Source: https://docs.jsonata.org/embedding-extending Demonstrates how bindings provided in the `evaluate` call override values assigned using `expression.assign`. ```javascript await expression.evaluate({}, {a: 109}); // 110 ``` -------------------------------- ### Group product sales by name with prices Source: https://docs.jsonata.org/sorting-grouping Groups product sales by 'Product Name' and collects all associated 'Price' values into an array for each product. Useful for seeing all prices for a given product name. ```JSONata Account.Order.Product { `Product Name`: Price } ``` -------------------------------- ### $random() Source: https://docs.jsonata.org/numeric-functions Generates a pseudo-random number between 0 (inclusive) and 1 (exclusive). ```APIDOC ## $random() ### Description Returns a pseudo random number greater than or equal to zero and less than one (`0 ≤ n < 1`). ### Signature `$random()` ### Parameters This function does not accept any parameters. ### Examples * `$random()` => `0.7973541067127` * `$random()` => `0.4029142127028` * `$random()` => `0.6558078550072 ``` -------------------------------- ### Get the type of a value in JSONata Source: https://docs.jsonata.org/object-functions Determines the type of a given value and returns it as a string. Supported types include 'null', 'number', 'string', 'boolean', 'array', 'object', and 'function'. Returns 'undefined' for undefined values. ```jsonata $type(null) ``` ```jsonata $type(123) ``` ```jsonata $type("hello") ``` ```jsonata $type(true) ``` ```jsonata $type([1, 2]) ``` ```jsonata $type({"a": 1}) ``` ```jsonata $type(function(){}) ``` ```jsonata $type(undefined) ``` -------------------------------- ### Pad String to a Specific Width (Left) Source: https://docs.jsonata.org/string-functions Pads a string on the left with spaces to reach a minimum width. Useful for aligning text. ```jsonata $pad("foo", -5) ``` -------------------------------- ### $formatNumber(number, picture [, options]) Source: https://docs.jsonata.org/numeric-functions Formats a number to a string according to a specified picture string, similar to the XPath/XQuery fn:format-number function. An optional options object can be provided to override locale-specific formatting characters. ```APIDOC ## $formatNumber(number, picture [, options]) ### Description Casts the `number` to a string and formats it to a decimal representation as specified by the `picture` string. The behavior is consistent with the XPath/XQuery function fn:format-number. The optional `options` argument can override default locale-specific formatting characters. ### Signature `$formatNumber(number, picture [, options])` ### Parameters #### Path Parameters - **number** (number) - Required - The number to format. - **picture** (string) - Required - The picture string defining the number format. - **options** (object) - Optional - An object containing name/value pairs to override default locale-specific formatting characters. ### Examples * `$formatNumber(12345.6, '#,###.00')` => `"12,345.60"` * `$formatNumber(1234.5678, "00.000e0")` => `"12.346e2"` * `$formatNumber(34.555, "#0.00;(#0.00)")` => `"34.56"` * `$formatNumber(-34.555, "#0.00;(#0.00)")` => `"(34.56)"` * `$formatNumber(0.14, "01%")` => `"14%"` * `$formatNumber(0.14, "###pm", {"per-mille": "pm"})` => `"140pm"` * `$formatNumber(1234.5678, "①①.①①①e①", {"zero-digit": "\u245f"})` => `"①②.③④⑥e②" ``` -------------------------------- ### Assign Function to Variable and Invoke Source: https://docs.jsonata.org/programming Shows how to assign an anonymous function to a variable and then invoke it within the same block. This allows for reuse of the function within its scope. ```JSONata ( $volume := function($l, $w, $h){ $l * $w * $h }; $volume(10, 10, 5); ) ``` -------------------------------- ### Factorial using tail recursion Source: https://docs.jsonata.org/programming Implements the factorial function using tail recursion with an accumulator. This optimized version avoids stack growth by performing calculations before the recursive call, allowing for indefinite recursion without stack overflow. ```JSONata ( $factorial := function($x){ $iter := function($x, $acc) { $x <= 1 ? $acc : $iter($x - 1, $x * $acc) }; $iter($x, 1) }; $factorial(170) ) ``` -------------------------------- ### Pad String to a Specific Width (Right) Source: https://docs.jsonata.org/string-functions Pads a string on the right with spaces to reach a minimum width. Useful for aligning text. ```jsonata $pad("foo", 5) ``` -------------------------------- ### Construct Single Object with Values as Arrays Source: https://docs.jsonata.org/construction To ensure all values in the constructed object are arrays, even if there's only one value for a key, use the array constructor syntax (e.g., `number[]`) within the object constructor. ```JSONata Phone{type: number[]} ``` -------------------------------- ### Pad Formatted Number with Leading Zeros Source: https://docs.jsonata.org/string-functions Formats a number to binary and then pads it with leading zeros to a specific width. Useful for fixed-width binary representations. ```jsonata $formatBase(35, 2) ~> $pad(-8, '0') ``` -------------------------------- ### Select First Array Element Source: https://docs.jsonata.org/simple Access the first object in the 'Phone' array using zero-based indexing. ```JSONata Phone[0] ``` -------------------------------- ### $spread() Source: https://docs.jsonata.org/object-functions Splits an object containing key/value pairs into an array of objects, each of which has a single key/value pair from the input object. If the parameter is an array of objects, then the resultant array contains an object for every key/value pair in every object in the supplied array. ```APIDOC ## $spread() ### Description Splits an `object` containing key/value pairs into an array of objects, each of which has a single key/value pair from the input `object`. If the parameter is an array of objects, then the resultant array contains an object for every key/value pair in every object in the supplied array. ### Signature `$spread(object)` ``` -------------------------------- ### Select First Element from Array of Fields Source: https://docs.jsonata.org/simple Uses parentheses to explicitly apply indexing to the array of 'number' fields, ensuring the first number is selected. ```JSONata (Phone.number)[0] ``` -------------------------------- ### $assert() Source: https://docs.jsonata.org/object-functions If condition is true, the function returns undefined. If the condition is false, an exception is thrown with the message as the message of the exception. ```APIDOC ## $assert() ### Description If condition is true, the function returns undefined. If the condition is false, an exception is thrown with the message as the message of the exception. ### Signature `$assert(condition, message)` ``` -------------------------------- ### Calculate Total Order Value (Price * Quantity) Source: https://docs.jsonata.org/sorting-grouping Use the $sum function with a calculated field to find the total value of each order, considering both price and quantity. This provides a more accurate order total. ```JSONata $sum(Account.Order.Product.(Price*Quantity)) ``` -------------------------------- ### Pad String with Custom Character (Left) Source: https://docs.jsonata.org/string-functions Pads a string on the left with a specified character to reach a minimum width. Useful for formatting numerical or identifier strings. ```jsonata $pad("foo", -5, "#") ``` -------------------------------- ### Map array with lambda function and context Source: https://docs.jsonata.org/higher-order-functions Uses a lambda function to format email addresses, including their index and the total count of items. ```JSONata $map(Email.address, function($v, $i, $a) { 'Item ' & ($i+1) & ' of ' & $count($a) & ': ' & $v }) ``` -------------------------------- ### Configure Sequence Length Guardrail Source: https://docs.jsonata.org/guardrails Set a maximum sequence length to prevent memory exhaustion from excessively long result sequences. Error D2015 is thrown if the limit is exceeded. ```javascript const jsonata = require('jsonata'); const data = {JSON: data}; const options = { sequence: 1e6 // maximum of one million items in a sequence }; (async () => { const expression = jsonata('', options); const result = await expression.evaluate(data); })() ``` -------------------------------- ### Format Number with Picture String Source: https://docs.jsonata.org/numeric-functions Formats a number to a string according to a specified picture string, similar to XPath's fn:format-number. Optional options can override locale-specific characters. ```jsonata $formatNumber(12345.6, '#,###.00') ``` ```jsonata $formatNumber(1234.5678, "00.000e0") ``` ```jsonata $formatNumber(34.555, "#0.00;(#0.00)") ``` ```jsonata $formatNumber(-34.555, "#0.00;(#0.00)") ``` ```jsonata $formatNumber(0.14, "01%") ``` ```jsonata $formatNumber(0.14, "###pm", {"per-mille": "pm"}) ``` ```jsonata $formatNumber(1234.5678, "①①.①①①e①", {"zero-digit": "\u245f"}) ``` -------------------------------- ### Cast to String with $string() Source: https://docs.jsonata.org/string-functions Use $string() to cast various data types to their string representation. The optional prettify argument formats JSON output. ```jsonata $string(5) ``` ```jsonata [1..5].$string() ``` -------------------------------- ### Function Composition: Uppercase and Trim Source: https://docs.jsonata.org/programming Combines the $uppercase and $trim functions into a new function $normalize using function composition via the chaining operator. This new function is then applied to a string with leading/trailing spaces. ```JSONata ( $normalize := $uppercase ~> $trim; $normalize(" Some Words ") ) ``` -------------------------------- ### Configure Stack Overflow Guardrail Source: https://docs.jsonata.org/guardrails Set a maximum stack limit to prevent expressions from causing a stack overflow. Error D1011 is thrown if the limit is exceeded. ```javascript const jsonata = require('jsonata'); const data = {JSON: data}; const options = { stack: 500 }; (async () => { const expression = jsonata('', options); const result = await expression.evaluate(data); })() ``` -------------------------------- ### Handle Non-existent Index Source: https://docs.jsonata.org/simple Attempting to access an index beyond the array bounds returns nothing. ```JSONata Phone[8] ``` -------------------------------- ### $lookup() Source: https://docs.jsonata.org/object-functions Returns the value associated with key in object. If the first argument is an array of objects, then all of the objects in the array are searched, and the values associated with all occurrences of key are returned. ```APIDOC ## $lookup() ### Description Returns the value associated with `key` in `object`. If the first argument is an array of objects, then all of the objects in the array are searched, and the values associated with all occurrences of `key` are returned. ### Signature `$lookup(object, key)` ``` -------------------------------- ### Format Integer to Roman Numerals Source: https://docs.jsonata.org/numeric-functions Casts a number to a string and formats it as Roman numerals using the 'I' picture string. This behavior is consistent with fn:format-integer. ```JSONata $formatInteger(1999, 'I') ``` -------------------------------- ### JSONata Comments and Function Definitions Source: https://docs.jsonata.org/programming Demonstrates the use of C-style comments within JSONata expressions and defines several functions including pi, plot, factorial, sine, and cosine. ```JSONata /* Long-winded expressions might need some explanation */ ( $pi := 3.1415926535897932384626; /* JSONata is not known for its graphics support! */ $plot := function($x) {( $floor := $string ~> $substringBefore(?, '.') ~> $number; $index := $floor(($x + 1) * 20 + 0.5); $join([0..$index].('.')) & 'O' & $join([$index..40].('.')) )}; /* Factorial is the product of the integers 1..n */ $product := function($a, $b) { $a * $b }; $factorial := function($n) { $n = 0 ? 1 : $reduce([1..$n], $product) }; $sin := function($x){ /* define sine in terms of cosine */ $cos($x - $pi/2) }; $cos := function($x){ /* Derive cosine by expanding Maclaurin series */ $x > $pi ? $cos($x - 2 * $pi) : $x < -$pi ? $cos($x + 2 * $pi) : $sum([0..12].($power(-1, $) * $power($x, 2*$) / $factorial(2*$))) }; [0..24].$sin($*$pi/12).$plot($) ) ``` -------------------------------- ### Select First Field from All Array Elements Source: https://docs.jsonata.org/simple Applies indexing to the array of 'number' fields obtained from all 'Phone' objects. This returns the first number from each 'Phone' object's number field, resulting in an array of numbers. ```JSONata Phone.number[0] ``` -------------------------------- ### Round Down to Nearest Integer with $floor() Source: https://docs.jsonata.org/numeric-functions Use $floor() to round a number down to the nearest integer that is less than or equal to the number. ```jsonata $floor(5) ``` ```jsonata $floor(5.3) ``` ```jsonata $floor(5.8) ``` ```jsonata $floor(-5.3) ``` -------------------------------- ### Context Variable Binding for Data Joins Source: https://docs.jsonata.org/path-operators Binds the current context item to a named variable for use in subsequent stages. Enables data joins by cross-referencing objects. ```jsonata library.loans@$l.books@$b[$l.isbn=$b.isbn].{ 'title': $b.title, 'customer': $l.customer } ``` -------------------------------- ### Split string by space with limit Source: https://docs.jsonata.org/string-functions Splits a string into an array of substrings using a space as the separator, limiting the number of resulting substrings. ```jsonata $split("so many words", " ", 2) ``` -------------------------------- ### Check if String Matches Regex (Case-Sensitive, No Match) Source: https://docs.jsonata.org/string-functions Returns false when the string does not match the provided regular expression. Demonstrates a negative case-sensitive regex match. ```jsonata $contains("abracadabra", /ar.*a/) ``` -------------------------------- ### Split string by multiple delimiters using regex Source: https://docs.jsonata.org/string-functions Splits a string into an array of substrings using a regular expression to match multiple delimiters (space, comma, period, semicolon). ```jsonata $split("too much, punctuation. hard; to read", /[ ,.;]+/) ``` -------------------------------- ### Select a Number Field Source: https://docs.jsonata.org/simple Extracts the value of the 'Age' field from the JSON document. ```JSONata Age ``` -------------------------------- ### Base64 Encode String Source: https://docs.jsonata.org/string-functions Converts an ASCII string to its base64 representation. Ensure all characters are within the 0x00 to 0xFF range. ```jsonata $base64encode("myuser:mypass") ``` -------------------------------- ### Configure Timeout Guardrail Source: https://docs.jsonata.org/guardrails Set a maximum time limit in milliseconds to prevent expressions from running excessively long. Error D1012 is thrown if the timeout is exceeded. It is good practice to specify both stack and timeout. ```javascript const jsonata = require('jsonata'); const data = {JSON: data}; const options = { stack: 500, timeout: 1000 // in milliseconds }; (async () => { const expression = jsonata('', options); const result = await expression.evaluate(data); })() ``` -------------------------------- ### Select Second Array Element Source: https://docs.jsonata.org/simple Access the second object in the 'Phone' array using zero-based indexing. ```JSONata Phone[1] ``` -------------------------------- ### Multiply price by quantity for each product in a group Source: https://docs.jsonata.org/sorting-grouping Calculates the total value (Price * Quantity) for each product within a group. For products with multiple entries, the results are collected into an array. ```JSONata Account.Order.Product { `Product Name`: $.(Price*Quantity) } ``` -------------------------------- ### Using Regex in Query Predicates Source: https://docs.jsonata.org/regex Demonstrates how to use a regular expression within a query predicate to filter objects based on a string property. The '~>' operator chains the regex function. ```JSONata Account.Order.Product[`Product Name` ~> /hat/i ] ``` -------------------------------- ### Find Minimum Number with $min() Source: https://docs.jsonata.org/aggregation-functions Use $min() to identify the smallest number in an array. This function expects an array of numbers; non-numeric elements will lead to an error. ```jsonata $min([5,1,3,7,4]) ``` -------------------------------- ### $keys() Source: https://docs.jsonata.org/object-functions Returns an array containing the keys in the object. If the argument is an array of objects, then the array returned contains a de-duplicated list of all the keys in all of the objects. ```APIDOC ## $keys() ### Description Returns an array containing the keys in the object. If the argument is an array of objects, then the array returned contains a de-duplicated list of all the keys in all of the objects. ### Signature `$keys(object)` ``` -------------------------------- ### Match occurrences with regex Source: https://docs.jsonata.org/string-functions Applies a regular expression to a string and returns an array of match details, including the matched substring, its index, and captured groups. ```JSONata $match("ababbabbcc",/a(b+)/) ``` -------------------------------- ### expression.evaluate(input[, bindings[, callback]]) Source: https://docs.jsonata.org/embedding-extending Executes the compiled JSONata expression against the provided input data. It can optionally accept bindings for variables and functions, and a callback for asynchronous execution. ```APIDOC ## expression.evaluate(input[, bindings[, callback]]) ### Description Runs the compiled JSONata expression against object `input` and returns the result as a new object. `input` should be a JavaScript value. `bindings`, if present, contain variable names and values (including functions) to be bound. If `callback(err, value)` is supplied, `expression.evaluate()` returns `undefined` and runs asynchronously. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **input** (any) - The JavaScript value (e.g., object, array) to evaluate the expression against. * **bindings** (object, optional) - An object containing variable names and their values (or functions) to be used during evaluation. Example: `{a: 4, b: () => 78}`. * **callback** (function, optional) - A callback function `(error, value)` that will be called upon completion for asynchronous execution. If provided, the method returns `undefined`. ### Usage **Synchronous:** ```javascript var result = await expression.evaluate({example: [{value: 4}, {value: 7}, {value: 13}]}); ``` **With Bindings:** ```javascript await jsonata("$a + $b()").evaluate({}, {a: 4, b: () => 78}); // returns 82 ``` **Asynchronous with Callback:** ```javascript await jsonata("7 + 12").evaluate({}, {}, (error, result) => { if(error) { console.error(error); return; } console.log("Finished with", result); }); console.log("Started"); ``` ### Response * **result** (any) - A new JavaScript value representing the result of the expression evaluation. ### Error Handling May throw a run-time `Error` with details like `code`, `stack`, `position`, `token`, and `message` if the expression encounters an issue during execution (e.g., attempting to invoke a non-function). ``` -------------------------------- ### Aggregate Array Values with $reduce() Source: https://docs.jsonata.org/higher-order-functions Use $reduce to aggregate values in an array by applying a function successively. The function takes an accumulator and the current value. An optional initial value can be provided. ```jsonata $product := function($i, $j){$i * $j}; $reduce([1..5], $product) ``` -------------------------------- ### Map array with string conversion Source: https://docs.jsonata.org/higher-order-functions Converts each number in a range to its string representation using the $string function. ```JSONata $map([1..5], $string) ``` -------------------------------- ### Select a String Field Source: https://docs.jsonata.org/simple Extracts the value of the 'Surname' field from the JSON document. ```JSONata Surname ``` -------------------------------- ### Spread an array of objects in JSONata Source: https://docs.jsonata.org/object-functions Creates an array of single-key/value pair objects from every key/value pair found in an array of input objects. ```jsonata $spread([{"a": 1, "b": 2}, {"c": 3}]) ``` -------------------------------- ### Evaluate with Bindings Source: https://docs.jsonata.org/embedding-extending Evaluates a JSONata expression with custom bindings for variables and functions. Bindings can include functions. ```javascript await jsonata("$a + $b()").evaluate({}, {a: 4, b: () => 78}); // returns 82 ``` -------------------------------- ### $type() Source: https://docs.jsonata.org/object-functions Evaluates the type of value and returns one of the following strings: "null", "number", "string", "boolean", "array", "object", "function". Returns (non-string) `undefined` when `value` is `undefined`. ```APIDOC ## $type() ### Description Evaluates the type of `value` and returns one of the following strings: * `"null"` * `"number"` * `"string"` * `"boolean"` * `"array"` * `"object"` * `"function"` Returns (non-string) `undefined` when `value` is `undefined`. ### Signature `$type(value)` ``` -------------------------------- ### HTML Page with JSONata Integration Source: https://docs.jsonata.org/using-browser This HTML page includes the JSONata library and a JavaScript function to evaluate a JSONata expression against user-provided JSON data. It's useful for simple client-side data transformations. ```html JSONata test

``` -------------------------------- ### Ternary Operator for Conditional Pricing Source: https://docs.jsonata.org/programming Use the ternary operator to assign 'Premium' or 'Basic' based on product price. This is useful for categorizing items based on a numerical threshold. ```JSONata Account.Order.Product.{ `Product Name`: $.Price > 100 ? "Premium" : "Basic" } ``` -------------------------------- ### Convert string to uppercase Source: https://docs.jsonata.org/string-functions Converts all characters in a string to uppercase. The context value is used if no string is provided. ```JSONata $uppercase("Hello World") ``` -------------------------------- ### Split string by space Source: https://docs.jsonata.org/string-functions Splits a string into an array of substrings using a space as the separator. ```jsonata $split("so many words", " ") ``` -------------------------------- ### Select City from Multiple Address Objects Source: https://docs.jsonata.org/construction Selects the 'City' value from both 'Address' and 'Other.Alternative.Address' objects, returning the results in a single array. This demonstrates selecting from different structures within the same expression. ```jsonata [Address, Other.`Alternative.Address`].City ``` ```json [ "Winchester", "London" ] ``` -------------------------------- ### Convert string to lowercase Source: https://docs.jsonata.org/string-functions Converts all characters in a string to lowercase. The context value is used if no string is provided. ```JSONata $lowercase("Hello World") ``` -------------------------------- ### Select 'ref' Field from First Object Source: https://docs.jsonata.org/simple Access the 'ref' field of the first object in a top-level array. This demonstrates chaining array indexing with field selection. ```JSONata $[0].ref ``` -------------------------------- ### Calculate Sum of Numbers with $sum() Source: https://docs.jsonata.org/aggregation-functions Use $sum() to compute the arithmetic sum of all numbers in an array. Ensure all array elements are numbers, as non-numeric items will cause an error. ```jsonata $sum([5,1,3,7,4]) ``` -------------------------------- ### Check if String Matches Regex (Case-Sensitive) Source: https://docs.jsonata.org/string-functions Returns true if the string matches the provided regular expression. This check is case-sensitive. ```jsonata $contains("abracadabra", /a.*a/) ``` -------------------------------- ### Check if String Matches Regex (Case-Sensitive, Partial Match) Source: https://docs.jsonata.org/string-functions Returns false because the regex does not match the entire string, even though parts of it are present. Demonstrates the need for precise regex patterns. ```jsonata $contains("Hello World", /wo/) ``` -------------------------------- ### Bind a function to a variable Source: https://docs.jsonata.org/other-operators Use the `:=` operator to bind a function definition to a variable. ```jsonata $square := function($n) { $n * $n } ``` -------------------------------- ### Replace using a function for complex transformations Source: https://docs.jsonata.org/string-functions Replaces matched substrings by invoking a function for each match. The function receives match details and returns the replacement string, enabling complex conditional logic or transformations. ```JSONata ( $convert := function($m) { ($number($m.groups[0]) - 32) * 5/9 & "C" }; $replace("temperature = 68F today", /(\d+)F/, $convert) ) ``` -------------------------------- ### Regex Syntax in JSONata Source: https://docs.jsonata.org/regex The basic syntax for defining a regular expression in JSONata, including optional flags for case-insensitivity and multiline matching. ```JSONata /regex/flags ```