### JMESPath Function Usage Example
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/api-reference.md
Demonstrates the use of built-in JMESPath functions, such as `max_by`, to perform operations on data. This example finds the item with the maximum value for a specified key.
```javascript
jmespath.search(
{"items": [{"value": 10}, {"value": 20}, {"value": 30}]},
"max_by(items, &value)"
);
// Returns: {"value": 30}
```
--------------------------------
### Install JMESPath.js in Node.js
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Use require to import the library in a Node.js environment. This is the standard way to include external modules.
```javascript
var jmespath = require('jmespath');
// Search with an expression
var result = jmespath.search(data, expression);
```
--------------------------------
### Operator Precedence Example
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/expression-syntax.md
Demonstrates operator precedence where AND has higher precedence than OR in a JMESPath expression.
```javascript
jmespath.search({a: 1, b: 2, c: 3}, "(a == `1` && b == `2`) || c == `10`");
// true (because the first part is true)
```
--------------------------------
### starts_with(haystack, needle)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Checks if a string begins with a specified prefix. Returns true if the string starts with the prefix, false otherwise.
```APIDOC
## starts_with(haystack, needle)
### Description
Check if a string starts with the specified prefix.
### Parameters
#### Path Parameters
- **haystack** (string) - Required - String to search in
- **needle** (string) - Required - Prefix to find
### Return Value
Returns `true` if the string starts with the prefix, `false` otherwise.
### Examples
```javascript
jmespath.search({name: "foobar"}, "starts_with(name, `'foo'`)"); // true
jmespath.search({name: "foobar"}, "starts_with(name, `'bar'`)"); // false
```
```
--------------------------------
### Check if String Starts With Prefix in JMESPath
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
The `starts_with` function checks if a given string begins with a specified prefix. It returns a boolean.
```javascript
jmespath.search({name: "foobar"}, "starts_with(name, `'foo'`)"); // true
jmespath.search({name: "foobar"}, "starts_with(name, `'bar'`)"); // false
```
--------------------------------
### Quickest Start: Execute a JMESPath Query
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/README.md
Demonstrates the basic usage of the `jmespath.search` function to query a JSON object. Ensure the 'jmespath' module is required before use.
```javascript
var jmespath = require('jmespath');
var result = jmespath.search(
{users: [{name: "Alice"}, {name: "Bob"}]},
"users[*].name"
);
// Returns: ["Alice", "Bob"]
```
--------------------------------
### JMESPath Expression to AST Structure
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
This example shows a complex JMESPath expression and its corresponding AST structure, illustrating the hierarchical representation of the expression.
```javascript
{
type: "Projection",
children: [
{
type: "FilterProjection",
children: [
{type: "Field", name: "items"},
{type: "Identity"},
{
type: "Comparator",
name: "GT",
children: [
{type: "Field", name: "price"},
{type: "Literal", value: 30}
]
}
]
},
{
type: "MultiSelectHash",
children: [
{
type: "KeyValuePair",
name: "name",
value: {type: "Field", name: "name"}
},
{
type: "KeyValuePair",
name: "cost",
value: {type: "Field", name: "price"}
}
]
}
]
}
```
--------------------------------
### Compile Expression with AND Operator
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Example of compiling a JMESPath expression using the AND operator.
```javascript
var ast = jmespath.compile("foo && bar");
// {
// type: "AndExpression",
// children: [
// {type: "Field", name: "foo"},
// {type: "Field", name: "bar"}
// ]
// }
```
--------------------------------
### JMESPath Simple Field Access Example
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/api-reference.md
Demonstrates basic field access in JMESPath. Use this for navigating nested JSON objects to retrieve specific values.
```javascript
var jmespath = require('jmespath');
// Simple field access
jmespath.search({foo: {bar: {baz: [0, 1, 2, 3, 4]}}}, "foo.bar.baz[2]");
// Returns: 2
```
--------------------------------
### Pipe Operator Example
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/expression-syntax.md
Use the pipe operator to pass the result of one expression as input to the next. This allows for sequential filtering and transformation of data.
```javascript
jmespath.search(
{items: [{values: [1, 2, 3]}, {values: [4, 5, 6]}]},
"items[*].values | [0]"
);
// [1, 4]
```
--------------------------------
### Select Object Property
Source: https://github.com/jmespath/jmespath.js/blob/master/README.md
Example of selecting a nested object property using a JMESPath expression.
```javascript
jmespath.search({foo: {bar: {baz: [0, 1, 2, 3, 4]}}}, "foo.bar")
```
--------------------------------
### Compile Expression with Comparator
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Example of compiling a JMESPath expression involving a greater than comparator.
```javascript
var ast = jmespath.compile("foo > `10`");
// {
// type: "Comparator",
// name: "GT",
// children: [
// {type: "Field", name: "foo"},
// {type: "Literal", value: 10}
// ]
// }
```
--------------------------------
### JMESPath Filter Projection Example
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/api-reference.md
Shows how to use filter projections to select elements from an array based on a condition. This is helpful for isolating data that meets specific criteria.
```javascript
jmespath.search(
{"foo": [{"age": 20}, {"age": 25}, {"age": 30}, {"age": 35}, {"age": 40}]},
"foo[?age > `30`]`"
);
// Returns: [{"age": 35}, {"age": 40}]
```
--------------------------------
### Get Object Keys with keys()
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Use the `keys` function to extract all keys from an object as an array. The order of keys is not guaranteed.
```javascript
jmespath.search({a: 1, b: 2, c: 3}, "keys(@)"); // ["a", "b", "c"] (order may vary)
```
--------------------------------
### Compile Expression with Pipe Operator
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Example of compiling a JMESPath expression using the pipe operator.
```javascript
var ast = jmespath.compile("foo | bar");
// {
// type: "Pipe",
// children: [
// {type: "Field", name: "foo"},
// {type: "Field", name: "bar"}
// ]
// }
```
--------------------------------
### Get Object Values with values()
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Use the `values` function to extract all values from an object as an array. The order of values is not guaranteed.
```javascript
jmespath.search({a: 1, b: 2, c: 3}, "values(@)"); // [1, 2, 3] (order may vary)
```
--------------------------------
### JMESPath Multi-Select Projection Example
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/api-reference.md
Illustrates multi-select projections to extract specific fields from a list of objects. This is useful when you need to collect a common attribute from multiple items in an array.
```javascript
jmespath.search(
{"foo": [{"first": "a", "last": "b"}, {"first": "c", "last": "d"}]},
"foo[*].first"
);
// Returns: ['a', 'c']
```
--------------------------------
### Compile Expression with OR Operator
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Example of compiling a JMESPath expression using the OR operator.
```javascript
var ast = jmespath.compile("foo || bar");
// {
// type: "OrExpression",
// children: [
// {type: "Field", name: "foo"},
// {type: "Field", name: "bar"}
// ]
// }
```
--------------------------------
### Example of Variadic Function Calls in JMESPath.js
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/types.md
Illustrates valid and invalid calls for a variadic function like `merge`. The function requires at least one argument, and subsequent arguments must match the specified variadic type.
```javascript
// merge(obj1: object, obj2?: object, ...): object
// Signature has last parameter with variadic: true
// Valid calls (1+ arguments)
jmespath.search({}, "merge(`{\"a\":1}`)");
jmespath.search({}, "merge(`{\"a\":1}`, `{\"b\":2}`)");
jmespath.search({}, "merge(`{\"a\":1}`, `{\"b\":2}`, `{\"c\":3}`)");
// Invalid calls (0 arguments, not enough)
jmespath.search({}, "merge()"); // ArgumentError
```
--------------------------------
### Example of Type Validation in JMESPath.js
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/types.md
Demonstrates valid and invalid calls to the `abs` function based on argument types. Invalid calls that do not match the expected signature will throw a `TypeError`.
```javascript
// Function: abs(number: number): number
// Signature: {types: [TYPE_NUMBER]}
// Valid calls
jmespath.search({n: 42}, "abs(n)"); // n is number, valid
jmespath.search({n: -5.5}, "abs(n)"); // n is number, valid
// Invalid calls (throw TypeError)
jmespath.search({s: "42"}, "abs(s)"); // s is string, invalid
jmespath.search({a: [1, 2]}, "abs(a)"); // a is array, invalid
```
--------------------------------
### Example of Unknown Function Error
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/errors.md
Demonstrates how an unknown function call within a JMESPath expression triggers an error. This occurs when the function name is not recognized by the JMESPath runtime.
```javascript
jmespath.search({}, "nonexistent_function()"); // Unknown function
```
--------------------------------
### Grouping and Aggregation with JMESPath
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
JMESPath can extract data for grouping in JavaScript or perform simple aggregations like sum. This example shows extracting all amounts and then summing them.
```javascript
var data = {
sales: [
{person: "Alice", amount: 100},
{person: "Bob", amount: 150},
{person: "Alice", amount: 200}
]
};
// Get all amounts (can then group in JavaScript)
jmespath.search(data, "sales[*].amount");
// [100, 150, 200]
// Sum all amounts
jmespath.search(data, "sum(sales[*].amount)");
// 450
```
--------------------------------
### Compile JMESPath Expression with Function Node
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Example of compiling a JMESPath expression that uses a function (`max_by`). The resulting AST shows the `Function` node with its name and children representing arguments.
```javascript
var ast = jmespath.compile("max_by(items, &age)");
// {
// type: "Function",
// name: "max_by",
// children: [
// {type: "Field", name: "items"},
// {type: "ExpressionReference", children: [{type: "Field", name: "age"}]}
// ]
// }
```
--------------------------------
### Get First Non-Null Argument with not_null
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Use the not_null function to return the first non-null argument provided. If all arguments are null, it returns null.
```javascript
jmespath.search({a: null, b: "value", c: 42}, "not_null(a, b, c)"); // "value"
```
```javascript
jmespath.search({a: null, b: null, c: 42}, "not_null(a, b, c)"); // 42
```
```javascript
jmespath.search({a: null, b: null}, "not_null(a, b)"); // null
```
--------------------------------
### String Functions in JMESPath.js
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Perform string operations like getting length, checking prefixes/suffixes, searching for substrings, joining elements, and reversing strings.
```javascript
// Length
jmespath.search({s: "hello"}, "length(s)"); // 5
// Starts/ends with
jmespath.search({s: "hello"}, "starts_with(s, `'he'`) "); // true
jmespath.search({s: "hello"}, "ends_with(s, `'lo'`) "); // true
// Contains
jmespath.search({s: "hello world"}, "contains(s, `'world'`) "); // true
// Join
jmespath.search({items: ["a", "b", "c"]}, "join(`','`, items)"); // "a,b,c"
// Reverse
jmespath.search({s: "hello"}, "reverse(s)"); // "olleh"
```
--------------------------------
### Compile JMESPath Expression with Flatten Operator
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Example of compiling a JMESPath expression that uses the flatten operator (`[]`). The resulting AST shows a `Projection` node containing a `Flatten` node.
```javascript
var ast = jmespath.compile("foo[]");
// {
// type: "Projection",
// children: [
// {type: "Flatten", children: [{type: "Field", name: "foo"}]},
// {type: "Identity"}
// ]
// }
```
--------------------------------
### TypeError: Wrong Type in max_by / min_by / createKeyFunction
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/errors.md
Shows a TypeError when using functions like `max_by()` where the expression for determining the key returns an incompatible type. This example uses `null` as a key, which is not a number or string.
```javascript
var data = {items: [{a: 1}, {a: null}]};
jmespath.search(data, "max_by(items, &a)"); // null is not number or string
```
--------------------------------
### Basic JMESPath Search
Source: https://github.com/jmespath/jmespath.js/blob/master/README.md
Demonstrates how to import jmespath.js and perform a basic search to select an element from a nested array.
```javascript
var jmespath = require('jmespath');
jmespath.search({foo: {bar: {baz: [0, 1, 2, 3, 4]}}}, "foo.bar.baz[2]")
```
--------------------------------
### Compile Expression with NOT Operator
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Example of compiling a JMESPath expression using the NOT operator.
```javascript
var ast = jmespath.compile("!foo");
// {
// type: "NotExpression",
// children: [
// {type: "Field", name: "foo"}
// ]
// }
```
--------------------------------
### Project Array Elements
Source: https://github.com/jmespath/jmespath.js/blob/master/README.md
Shows how to project a specific property from each element in an array using JMESPath.
```javascript
jmespath.search({"foo": [{"first": "a", "last": "b"},
{"first": "c", "last": "d"}]},
"foo[*].first")
```
--------------------------------
### Array Operations with JMESPath
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Illustrates array indexing (including negative indices) and slicing using JMESPath expressions. Supports various slicing syntaxes like step and reverse.
```javascript
// Array indexing
jmespath.search({items: [10, 20, 30]}, "items[0]"); // 10
jmespath.search({items: [10, 20, 30]}, "items[-1]"); // 30
// Array slicing
jmespath.search({items: [0, 1, 2, 3, 4, 5]}, "items[1:4]"); // [1, 2, 3]
jmespath.search({items: [0, 1, 2, 3, 4, 5]}, "items[::2]"); // [0, 2, 4]
jmespath.search({items: [0, 1, 2, 3, 4, 5]}, "items[::-1]"); // [5, 4, 3, 2, 1, 0]
```
--------------------------------
### Get Type of Expression in JMESPath
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Use the `type` function to determine the data type of an expression. It returns a string representing the type.
```javascript
jmespath.search({}, "type(@)"); // "object"
jmespath.search([], "type(@)"); // "array"
jmespath.search("foo", "type(@)"); // "string"
jmespath.search(42, "type(@)"); // "number"
jmespath.search(true, "type(@)"); // "boolean"
jmespath.search(null, "type(@)"); // "null"
```
--------------------------------
### Tokenize JMESPath Expression
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Tokenize a JMESPath expression to get an array of token objects. This is useful for debugging or custom parsing logic.
```javascript
var tokens = jmespath.tokenize("foo.bar[?age > `30`].name");
console.log(tokens);
// Array of token objects with type, value, and start position
```
--------------------------------
### Include JMESPath.js in the Browser
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Include the library using a script tag in your HTML for browser-based usage. The search function will be available globally.
```html
```
--------------------------------
### Load JMESPath.js in HTML
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Include the jmespath.js script in your HTML file to make the library available globally. This is suitable for simple web pages.
```html
```
--------------------------------
### Basic JMESPath Search
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Perform a basic search operation using the jmespath.search function with sample data and a simple expression. This demonstrates the core functionality.
```javascript
var data = {
foo: {
bar: {
baz: [0, 1, 2, 3, 4]
}
}
};
var result = jmespath.search(data, "foo.bar.baz[2]");
console.log(result); // 2
```
--------------------------------
### compile(expr)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/README.md
Parses a JMESPath expression into an Abstract Syntax Tree (AST).
```APIDOC
## compile(expr)
### Description
Parses a JMESPath expression into an Abstract Syntax Tree (AST).
### Parameters
- **expr** (string) - The JMESPath expression to parse.
### Returns
(object) - The AST representation of the expression.
```
--------------------------------
### Get Absolute Value of a Number
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Use the `abs` function to return the absolute value of a given number. This is useful for ensuring positive results from calculations.
```javascript
jmespath.search({n: -5}, "abs(n)"); // 5
jmespath.search({n: 3.14}, "abs(n)"); // 3.14
```
--------------------------------
### Define Function Signature in JavaScript
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/types.md
Defines a function implementation and its expected parameter types using `_func` and `_signature`. The `types` array lists acceptable types for each parameter.
```javascript
{
_func: functionImplementation,
_signature: [
{types: [TYPE_NUMBER]},
{types: [TYPE_STRING, TYPE_ARRAY]},
// ... more parameter signatures
]
}
```
--------------------------------
### Catching ArgumentError in JMESPath
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/errors.md
Demonstrates how to catch and handle ArgumentErrors that may occur during JMESPath searches. This pattern allows for graceful error management by checking the error name.
```javascript
try {
jmespath.search(data, expression);
} catch (e) {
if (e.name === "ArgumentError") {
// Handle argument errors
console.log("Argument error:", e.message);
}
}
```
--------------------------------
### Get Length of Array/String/Object
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Use the `length` function to determine the number of elements in an array, characters in a string, or keys in an object. Returns null for unsupported types.
```javascript
jmespath.search({s: "hello"}, "length(s)"); // 5
jmespath.search({a: [1, 2, 3, 4]}, "length(a)"); // 4
jmespath.search({o: {a: 1, b: 2}}, "length(o)"); // 2
```
--------------------------------
### Convert String to Number with JMESPath
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/types.md
Shows how to use the `to_number()` function for explicit type conversion in JMESPath. This is necessary for comparisons between strings and numbers.
```javascript
jmespath.search({s: "42"}, "to_number(s) == `42`"); // true
```
--------------------------------
### Type Functions
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/types.md
Includes functions for type checking and type conversion.
```APIDOC
## Type Functions
### type
#### Signature
`(TYPE_ANY) → string`
### to_string
#### Signature
`(TYPE_ANY) → string`
### to_number
#### Signature
`(TYPE_ANY) → number | null`
### not_null
#### Signature
`(TYPE_ANY, TYPE_ANY...) → any` (variadic)
```
--------------------------------
### Implement Try-Catch for Safe JMESPath Searches
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Use a try-catch block to gracefully handle potential errors during JMESPath searches. This pattern is useful for preventing application crashes when an invalid expression or data structure is encountered. It returns null and logs the error to the console.
```javascript
function safeSearch(data, expression) {
try {
return jmespath.search(data, expression);
} catch (e) {
console.error("JMESPath error:", e.name, "-", e.message);
return null;
}
}
// Usage
var result = safeSearch(data, "foo.bar[?baz > `10`]");
```
--------------------------------
### ArgumentError: Too Few Arguments to Variadic Function
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/errors.md
This error occurs when a variadic function is called with fewer arguments than its minimum requirement. For example, 'merge()' needs at least one argument.
```javascript
jmespath.search({}, "merge()"); // merge() requires at least 1 argument
```
--------------------------------
### join(separator, array)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Joins the elements of an array into a single string, using a specified separator between elements.
```APIDOC
## join(separator, array)
### Description
Join array elements into a string using a separator.
### Parameters
#### Path Parameters
- **separator** (string) - Required - String to join elements with
- **array** (Array) - Required - Array of strings to join
### Return Value
Returns a single string with array elements joined by the separator.
### Examples
```javascript
jmespath.search({items: ["a", "b", "c"]}, "join(`','`, items)"); // "a,b,c"
jmespath.search({items: ["a", "b", "c"]}, "join(`' '`, items)"); // "a b c"
```
```
--------------------------------
### TypeError: Wrong Argument Type for Function
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/errors.md
Example of a TypeError where a function receives an argument of an incorrect type. This specific case shows the `abs()` function expecting a number but receiving a string.
```javascript
jmespath.search({}, "abs(`'string'`);"); // abs() expects number, got string
```
--------------------------------
### keys(object)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Returns all keys from an object as an array. The order of keys is not guaranteed.
```APIDOC
## keys(object)
### Description
Returns all keys from an object as an array.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Method
Not applicable (function call within JMESPath expression)
### Endpoint
Not applicable
### Request Example
```javascript
jmespath.search({a: 1, b: 2, c: 3}, "keys(@)");
// Expected output: ["a", "b", "c"] (order may vary)
```
### Response
#### Success Response
- **keys** (Array) - An array containing the keys of the input object.
#### Response Example
```json
["a", "b", "c"]
```
```
--------------------------------
### Expression Reference for Functions
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/expression-syntax.md
Create a reference to an expression using the '&' symbol. This is essential for passing expressions as arguments to functions like sort_by, max_by, and min_by.
```javascript
jmespath.search(
{items: [{a: 5}, {a: 2}, {a: 8}]},
"sort_by(items, &a)"
);
// [{a: 2}, {a: 5}, {a: 8}]
```
```javascript
jmesmespath.search(
{items: [{price: 10}, {price: 5}, {price: 20}]},
"max_by(items, &price)"
);
// {price: 20}
```
--------------------------------
### TypeError: Wrong Type in sort_by Result
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/errors.md
Illustrates a TypeError occurring in `sort_by()` when the expression used for sorting evaluates to a type other than a number or string. This example shows sorting by a key that results in an object.
```javascript
var data = {items: [{a: 1}, {a: []}]};
jmespath.search(data, "sort_by(items, &a)"); // Expected number or string
```
--------------------------------
### Compare Same and Different Types in JMESPath
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/types.md
Illustrates JMESPath's strict type comparison rules. Different types are never equal, and comparisons like less than or greater than require comparable types.
```javascript
jmespath.search({}, "`1` == `'1'`"); // false (number != string)
jmespath.search({}, "`1` == `1`"); // true (same types)
```
--------------------------------
### Filter and Transform Array Elements
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Combine filtering conditions with projections to extract specific data from array elements that meet certain criteria. This example retrieves the IDs of completed orders with a total greater than 100.
```javascript
var data = {
orders: [
{id: 1, total: 100, status: "completed"},
{id: 2, total: 50, status: "pending"},
{id: 3, total: 200, status: "completed"}
]
};
// Get names of high-value completed orders
jmespath.search(
data,
"orders[?status == `'completed'` && total > `100`].id"
);
// [3]
```
--------------------------------
### MultiSelectHash AST Node
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Represents selecting multiple key-value pairs and returning them as an object. Created by brace notation like `{key1: foo, key2: bar}`.
```javascript
{
type: "MultiSelectHash",
children: [
{type: "KeyValuePair", name: "key1", value: expr1},
{type: "KeyValuePair", name: "key2", value: expr2},
...
]
}
```
```javascript
var ast = jmespath.compile("{x: foo, y: bar}");
// {
// type: "MultiSelectHash",
// children: [
// {type: "KeyValuePair", name: "x", value: {type: "Field", name: "foo"}},
// {type: "KeyValuePair", name: "y", value: {type: "Field", name: "bar"}}
// ]
// }
```
--------------------------------
### JMESPath Multi-Select
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Demonstrates selecting multiple fields from an object, returning them as an array or a new object. Also shows multi-select with projection on arrays.
```javascript
// Return multiple fields as an array
jmespath.search({a: 1, b: 2, c: 3}, "[a, b]");
// [1, 2]
// Return multiple fields as an object
jmespath.search({name: "John", age: 30, city: "NYC"}, "{person_name: name, person_age: age}");
// {person_name: "John", person_age: 30}
// Multi-select with projection
jmespath.search(
{people: [{id: 1, name: "Alice"}, {id: 2, name: "Bob"}]},
"people[*].{id: id, person_name: name}"
);
// [{id: 1, person_name: "Alice"}, {id: 2, person_name: "Bob"}]
```
--------------------------------
### Tokenize JMESPath Expression
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/api-reference.md
Use `jmespath.tokenize` to break down a JMESPath expression string into an array of token objects. Each token includes its `type`, `value`, and `start` position in the original expression. This is helpful for lexer-level analysis or debugging.
```javascript
var jmespath = require('jmespath');
// Tokenize simple field access
jmespath.tokenize("foo.bar");
// Returns:
// [
// {type: "UnquotedIdentifier", value: "foo", start: 0},
// {type: "Dot", value: ".", start: 3},
// {type: "UnquotedIdentifier", value: "bar", start: 4}
// ]
```
```javascript
var jmespath = require('jmespath');
// Tokenize array index
jmespath.tokenize("foo[0]");
// Returns:
// [
// {type: "UnquotedIdentifier", value: "foo", start: 0},
// {type: "Lbracket", value: "[", start: 3},
// {type: "Number", value: 0, start: 4},
// {type: "Rbracket", value: "]", start: 5}
// ]
```
```javascript
var jmespath = require('jmespath');
// Tokenize with literals
jmespath.tokenize("`[1, 2, 3]`");
// Returns:
// [
// {type: "Literal", value: [1, 2, 3], start: 0}
// ]
```
--------------------------------
### Wildcard Projection with JMESPath
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/expression-syntax.md
Project over all elements or values in an array or object using the wildcard '*'.
```javascript
jmespath.search(
{items: [{a: 1}, {a: 2}, {a: 3}]},
"items[*].a"
);
// [1, 2, 3]
```
```javascript
jmespath.search(
{foo: {a: 1, b: 2, c: 3}},
"foo.*"
);
// [1, 2, 3]
```
--------------------------------
### Convert to String with to_string()
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Use to_string() to convert any value to its string representation. If the value is already a string, it is returned unchanged. Otherwise, a JSON string representation is returned.
```javascript
jmespath.search({n: 42}, "to_string(n)"); // "42"
jmespath.search({s: "hello"}, "to_string(s)"); // "hello"
jmespath.search({a: [1, 2, 3]}, "to_string(a)"); // "[1,2,3]"
```
--------------------------------
### Object Functions
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/types.md
Provides utilities for extracting keys and values from objects, and merging objects.
```APIDOC
## Object Functions
### keys
#### Signature
`(TYPE_OBJECT) → array`
### values
#### Signature
`(TYPE_OBJECT) → array`
### merge
#### Signature
`(TYPE_OBJECT, TYPE_OBJECT...) → object` (variadic)
```
--------------------------------
### JMESPath Projections
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Demonstrates wildcard and object value projections to extract specific data from arrays of objects or entire objects.
```javascript
// Wildcard projection
var data = {
people: [
{name: "Alice", age: 30},
{name: "Bob", age: 25},
{name: "Charlie", age: 35}
]
};
jmespath.search(data, "people[*].name");
// ["Alice", "Bob", "Charlie"]
// Object value projection
jmespath.search({a: 1, b: 2, c: 3}, ".*"); // [1, 2, 3]
```
--------------------------------
### Search Data with JMESPath Expression
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/INDEX.md
Use this for basic data querying with JMESPath. Requires the JMESPath library to be imported.
```javascript
jmespath.search(data, "foo.bar[*].baz")
```
--------------------------------
### Multi-select hash from array elements
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/expression-syntax.md
Apply a multi-select hash expression to each element of an array to create new objects with specified keys and values extracted from the original objects.
```javascript
jmespath.search(
{items: [{name: "item1", id: 1}, {name: "item2", id: 2}]},
"items[*].{name: name, identifier: id}"
);
// [{name: "item1", identifier: 1}, {name: "item2", identifier: 2}]
```
--------------------------------
### values(object)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Returns all values from an object as an array. The order of values corresponds to the order of keys.
```APIDOC
## values(object)
### Description
Returns all values from an object as an array.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Method
Not applicable (function call within JMESPath expression)
### Endpoint
Not applicable
### Request Example
```javascript
jmespath.search({a: 1, b: 2, c: 3}, "values(@)");
// Expected output: [1, 2, 3] (order may vary)
```
### Response
#### Success Response
- **values** (Array) - An array containing the values of the input object.
#### Response Example
```json
[1, 2, 3]
```
```
--------------------------------
### tokenize(expr)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/README.md
Lexes a JMESPath expression into a list of tokens.
```APIDOC
## tokenize(expr)
### Description
Lexes a JMESPath expression into a list of tokens.
### Parameters
- **expr** (string) - The JMESPath expression to tokenize.
### Returns
(array) - An array of tokens.
```
--------------------------------
### Comparison Functions
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/types.md
Enables comparison operations between strings, arrays, and any data type.
```APIDOC
## Comparison Functions
### contains
#### Signature
`(TYPE_STRING | TYPE_ARRAY, TYPE_ANY) → boolean`
### starts_with
#### Signature
`(TYPE_STRING, TYPE_STRING) → boolean`
### ends_with
#### Signature
`(TYPE_STRING, TYPE_STRING) → boolean`
```
--------------------------------
### Array Functions
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/types.md
Offers a variety of functions for manipulating and querying arrays and strings.
```APIDOC
## Array Functions
### length
#### Signature
`(TYPE_STRING | TYPE_ARRAY | TYPE_OBJECT) → number`
### reverse
#### Signature
`(TYPE_STRING | TYPE_ARRAY) → string | array`
### sort
#### Signature
`(TYPE_ARRAY_NUMBER | TYPE_ARRAY_STRING) → array`
### sort_by
#### Signature
`(TYPE_ARRAY, TYPE_EXPREF) → array`
### max
#### Signature
`(TYPE_ARRAY_NUMBER | TYPE_ARRAY_STRING) → number | string | null`
### max_by
#### Signature
`(TYPE_ARRAY, TYPE_EXPREF) → object | null`
### min
#### Signature
`(TYPE_ARRAY_NUMBER | TYPE_ARRAY_STRING) → number | string | null`
### min_by
#### Signature
`(TYPE_ARRAY, TYPE_EXPREF) → object | null`
### join
#### Signature
`(TYPE_STRING, TYPE_ARRAY_STRING) → string`
### to_array
#### Signature
`(TYPE_ANY) → array`
```
--------------------------------
### search(data, expr)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/README.md
Executes a JMESPath query against the provided data.
```APIDOC
## search(data, expr)
### Description
Executes a JMESPath query against the provided data.
### Parameters
- **data** (object | array) - The JSON data to query.
- **expr** (string) - The JMESPath expression to execute.
### Returns
(any) - The result of the query.
```
--------------------------------
### Use JMESPath.js with Modern Bundlers
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Import JMESPath.js using ES6 import syntax when working with modern JavaScript build tools like webpack. This is the recommended approach for most projects.
```javascript
// With npm/webpack
import jmespath from 'jmespath';
const data = {foo: {bar: "baz"}};
const result = jmespath.search(data, "foo.bar");
```
--------------------------------
### Aggregation Functions in JMESPath.js
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Use sum, avg, min, and max to perform aggregate calculations on arrays. Max by expression finds the maximum element based on a specified field.
```javascript
// Sum
jmespath.search({nums: [1, 2, 3, 4, 5]}, "sum(nums)"); // 15
// Average
jmespath.search({nums: [10, 20, 30]}, "avg(nums)"); // 20
// Min/Max
jmespath.search({nums: [3, 1, 4, 1, 5]}, "min(nums)"); // 1
jmespath.search({nums: [3, 1, 4, 1, 5]}, "max(nums)"); // 5
// Max by expression
var data = {employees: [{name: "Alice", salary: 50000}, {name: "Bob", salary: 60000}]};
jmespath.search(data, "max_by(employees, &salary)");
// {name: "Bob", salary: 60000}
```
--------------------------------
### Compile Projection AST
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Compiles a JMESPath expression involving a wildcard projection into its AST representation. The AST shows the structure of the expression, breaking down the projection into its base and projected fields.
```javascript
var ast = jmespath.compile("foo[*].bar");
// {
// type: "Projection",
// children: [
// {type: "Field", name: "foo"},
// {type: "Field", name: "bar"}
// ]
// }
```
--------------------------------
### Pre-compile JMESPath Expressions
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
For expressions used repeatedly, compile them once to avoid recompilation overhead. However, direct AST evaluation is not exposed; `search()` is generally preferred.
```javascript
// Bad: compiles expression each time
for (var i = 0; i < 1000; i++) {
var result = jmespath.search(data[i], "foo.bar[*].baz");
}
// Good: compile once, reuse AST
var ast = jmespath.compile("foo.bar[*].baz");
// However, direct evaluation of AST requires internal APIs
// It's still better to use search() for most cases
```
--------------------------------
### MultiSelectList AST Node
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Represents selecting multiple expressions and returning them as an array. Created by bracket notation like `[foo, bar, baz]`.
```javascript
{
type: "MultiSelectList",
children: [expr1, expr2, expr3, ...]
}
```
```javascript
var ast = jmespath.compile("[foo, bar]");
// {
// type: "MultiSelectList",
// children: [
// {type: "Field", name: "foo"},
// {type: "Field", name: "bar"}
// ]
// }
```
--------------------------------
### Compile JMESPath Expression to AST
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Use the `jmespath.compile()` function to convert a JMESPath expression string into its Abstract Syntax Tree (AST) representation. The resulting AST can then be logged or further processed.
```javascript
var ast = jmespath.compile("foo.bar[?baz > `10`].qux");
console.log(JSON.stringify(ast, null, 2));
```
--------------------------------
### min(array)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Returns the minimum value from an array of numbers or strings. Returns null if the array is empty.
```APIDOC
## min(array)
### Description
Return the minimum value from an array of numbers or strings.
### Parameters
#### Path Parameters
- **array** (Array | Array) - Required - Array of numbers or strings
### Return Value
Returns the minimum value, or `null` if the array is empty.
### Examples
```javascript
jmespath.search({nums: [3, 1, 4, 1, 5, 9]}, "min(nums)"); // 1
jmespath.search({strs: ["z", "a", "m"]}, "min(strs)"); // "a"
jmespath.search({nums: []}, "min(nums)"); // null
```
```
--------------------------------
### Compile and Tokenize JMESPath Expressions
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/INDEX.md
Compile expressions for repeated use or tokenize them for analysis. These are advanced features for performance optimization or introspection.
```javascript
jmespath.compile("complex.expression")
```
```javascript
jmespath.tokenize("expression")
```
--------------------------------
### Type Conversion and Checking in JMESPath.js
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Convert data types using to_string, to_number, and to_array. Check the type of a value using the type function.
```javascript
// to_string
jmespath.search({n: 42}, "to_string(n)"); // "42"
// to_number
jmespath.search({s: "42"}, "to_number(s)"); // 42
// to_array
jmespath.search({n: 42}, "to_array(n)"); // [42]
// Type checking
jmespath.search({x: 42}, "type(x)"); // "number"
jmespath.search({x: "hello"}, "type(x)"); // "string"
```
--------------------------------
### to_string(value)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Converts a given value to its string representation. If the value is already a string, it is returned unchanged. Otherwise, a JSON string representation is returned.
```APIDOC
## to_string(value)
### Description
Converts a given value to its string representation. If the value is already a string, it is returned unchanged. Otherwise, a JSON string representation is returned.
### Parameters
#### Path Parameters
- **value** (any) - Required - Value to convert
### Return Value
Returns the string representation of the value.
### Examples
```javascript
jmespath.search({n: 42}, "to_string(n)"); // "42"
jmespath.search({s: "hello"}, "to_string(s)"); // "hello"
jmespath.search({a: [1, 2, 3]}, "to_string(a)"); // "[1,2,3]"
```
```
--------------------------------
### Compile ValueProjection AST
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Compiles a JMESPath expression involving a value projection into its AST representation. The AST structure reflects the projection over object values.
```javascript
var ast = jmespath.compile("foo.*");
// {
// type: "ValueProjection",
// children: [
// {type: "Field", name: "foo"},
// {type: "Identity"}
// ]
// }
```
--------------------------------
### Pass Expressions as Function Arguments
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Use the '&' symbol to pass JMESPath expressions as arguments to built-in functions like `max_by` and `sort_by`. This allows for dynamic sorting and finding maximums based on specific fields.
```javascript
var data = {
items: [
{name: "Item A", priority: 5},
{name: "Item B", priority: 2},
{name: "Item C", priority: 8}
]
};
// Find item with highest priority
jmespath.search(data, "max_by(items, &priority)");
// {name: "Item C", priority: 8}
// Sort by priority
jmespath.search(data, "sort_by(items, &priority)");
// [{name: "Item B", priority: 2}, {name: "Item A", priority: 5}, {name: "Item C", priority: 8}]
```
--------------------------------
### Multi-select list from object
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/expression-syntax.md
Select multiple fields from a JSON object and return them as an array. This is useful for extracting specific properties.
```javascript
jmespath.search({foo: "a", bar: "b", baz: "c"}, "[foo, bar]");
// ["a", "b"]
```
--------------------------------
### Catching RuntimeError in JMESPath.js
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/errors.md
Demonstrates how to catch and handle RuntimeError exceptions when evaluating JMESPath expressions. This is useful for debugging invalid expressions or unexpected evaluation issues.
```javascript
try {
jmespath.search(data, expression);
} catch (e) {
if (e.name === "RuntimeError") {
// Handle runtime errors
console.log("Runtime error:", e.message);
}
}
```
--------------------------------
### Compile JMESPath Expression with ExpressionReference
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/ast-nodes.md
Demonstrates compiling an expression that uses `&` to reference a field within a function's arguments. The AST includes an `ExpressionReference` node.
```javascript
var ast = jmespath.compile("sort_by(items, &price)");
// Function children would include:
// {
// type: "ExpressionReference",
// children: [
// {type: "Field", name: "price"}
// ]
// }
```
--------------------------------
### sum(array)
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/functions.md
Calculates and returns the sum of all numbers within an array. Ideal for aggregating numerical values in a dataset.
```APIDOC
## sum(array)
### Description
Return the sum of an array of numbers.
### Parameters
#### Path Parameters
- **array** (Array) - Required - Array of numbers
### Return Value
Returns the sum as a number.
### Request Example
```javascript
jmespath.search({nums: [1, 2, 3, 4, 5]}, "sum(nums)");
jmespath.search({nums: [10, 20, 30]}, "sum(nums)");
```
### Response Example
```json
{
"example": 15
}
```
```
--------------------------------
### JMESPath Filtering
Source: https://github.com/jmespath/jmespath.js/blob/master/_autodocs/usage-guide.md
Shows how to filter arrays based on conditions, including simple boolean checks, numeric comparisons, and complex logical operations (AND, OR).
```javascript
var data = {
products: [
{name: "Widget", price: 10, in_stock: true},
{name: "Gadget", price: 20, in_stock: false},
{name: "Doohickey", price: 15, in_stock: true}
]
};
// Simple filter
jmespath.search(data, "products[?in_stock].name");
// ["Widget", "Doohickey"]
// Numeric comparison
jmespath.search(data, "products[?price > `15`]");
// [{name: "Gadget", price: 20, in_stock: false}]
// Complex conditions
jmespath.search(data, "products[?price > `10` && in_stock == `true`].name");
// ["Widget", "Doohickey"]
// Filter with OR
jmespath.search(data, "products[?price < `12` || price > `18`].name");
// ["Widget", "Gadget"]
```