JSON query and transformation language for extracting, filtering, and transforming JSON data
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core functionality for creating and evaluating JSONata expressions against JSON data.
Creates a JSONata expression object from a query string.
/**
* Create a JSONata expression object
* @param expression - JSONata query expression string
* @param options - Optional configuration object
* @returns Expression object with evaluation methods
*/
function jsonata(expression, options);Parameters:
expression (string): JSONata query expression to parseoptions (object, optional): Configuration options
recover (boolean, optional): Attempt to recover on parse errorsRegexEngine (RegExp, optional): Custom regex engine constructorReturns: Expression object with methods for evaluation and manipulation
Usage Examples:
const jsonata = require("jsonata");
// Basic expression creation
const expr1 = jsonata("Account.Order[0].Product");
// With recovery option for error handling
const expr2 = jsonata("potentially.invalid[syntax", { recover: true });
// With custom regex engine
const expr3 = jsonata('$match(text, /pattern/)', { RegexEngine: MyRegExp });Evaluates the expression against input data with optional variable bindings.
/**
* Evaluate expression against input data
* @param input - Input data to evaluate against
* @param bindings - Optional variable bindings
* @param callback - Optional Node.js-style callback
* @returns Promise resolving to evaluation result, or calls callback
*/
evaluate(input: any, bindings?: Record<string, any>): Promise<any>;
evaluate(input: any, bindings: Record<string, any> | undefined, callback: (err: JsonataError, resp: any) => void): void;Parameters:
input (any): Input data to evaluate the expression againstbindings (object, optional): Object containing variable name-value pairscallback (function, optional): Node.js-style callback (error, result) => voidReturns: Promise<any> when used without callback, or calls callback with result
Usage Examples:
const data = {
users: [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 }
]
};
// Basic evaluation
const expr = jsonata("users[age > 25].name");
const result = await expr.evaluate(data); // ["Alice"]
// With variable bindings
const expr2 = jsonata("users[age > $threshold].name");
const result2 = await expr2.evaluate(data, { threshold: 27 }); // ["Alice"]
// With callback (Node.js style)
expr.evaluate(data, {}, (err, result) => {
if (err) {
console.error("Evaluation error:", err);
} else {
console.log("Result:", result);
}
});Assigns a variable in the expression's evaluation environment.
/**
* Assign a variable in the expression environment
* @param name - Variable name
* @param value - Variable value
*/
assign(name: string, value: any): void;Parameters:
name (string): Variable name to assignvalue (any): Value to assign to the variableUsage Examples:
const expr = jsonata("$greeting & ' ' & name & '!'");
expr.assign("greeting", "Hello");
const result = await expr.evaluate({ name: "World" }); // "Hello World!"
// Multiple assignments
expr.assign("prefix", "Mr.");
expr.assign("suffix", "Esq.");Registers a custom function in the expression's evaluation environment.
/**
* Register a custom function in the expression environment
* @param name - Function name
* @param implementation - Function implementation
* @param signature - Optional function signature for validation
*/
registerFunction(name: string, implementation: Function, signature?: string): void;Parameters:
name (string): Function name (will be callable as $name in expressions)implementation (function): Function implementationsignature (string, optional): Function signature for parameter validationUsage Examples:
// Register a simple function
expr.registerFunction("double", (x) => x * 2);
// Now usable as: $double(5) returns 10
// Register function with signature validation
expr.registerFunction("add", (a, b) => a + b, "<nn:n>");
// Signature: takes two numbers, returns number
// Register async function
expr.registerFunction("delay", async (ms) => {
await new Promise(resolve => setTimeout(resolve, ms));
return "completed";
});
// Function with access to evaluation context
expr.registerFunction("contextAware", function(value) {
// 'this' refers to Focus object with environment and input
const input = this.input;
const env = this.environment;
return { value, hasInput: input !== undefined };
});Returns the abstract syntax tree of the parsed expression.
/**
* Get the abstract syntax tree of the expression
* @returns ExprNode representing the parsed expression
*/
ast(): ExprNode;Returns: ExprNode object representing the expression's AST
Usage Examples:
const expr = jsonata("users[0].name");
const ast = expr.ast();
console.log(ast.type); // "path"
console.log(ast.steps); // Array of path steps
// Useful for expression analysis and debugging
function analyzeExpression(expression) {
const expr = jsonata(expression);
const ast = expr.ast();
return {
type: ast.type,
complexity: countNodes(ast),
hasVariables: hasVariableReferences(ast)
};
}Returns any parse errors from the expression compilation.
/**
* Get parse errors from expression compilation
* @returns Array of errors or undefined if no errors
*/
errors(): any;Returns: Array of error objects or undefined if expression parsed successfully
Usage Examples:
// Check for parse errors
const expr = jsonata("invalid[syntax");
const errors = expr.errors();
if (errors) {
errors.forEach(error => {
console.log(`Error at position ${error.position}: ${error.message}`);
});
} else {
console.log("Expression parsed successfully");
}
// Error handling workflow
function createSafeExpression(expressionStr) {
try {
const expr = jsonata(expressionStr);
const errors = expr.errors();
if (errors) {
throw new Error(`Parse errors: ${errors.map(e => e.message).join(", ")}`);
}
return expr;
} catch (error) {
console.error("Failed to create expression:", error.message);
return null;
}
}interface JsonataOptions {
recover?: boolean; // Attempt to recover on parse errors
RegexEngine?: RegExp; // Custom regex engine constructor
}
interface Expression {
evaluate(input: any, bindings?: object, callback?: function): Promise<any>;
assign(name: string, value: any): void;
registerFunction(name: string, implementation: function, signature?: string): void;
ast(): ExprNode;
errors(): JsonataError[] | undefined;
}
interface ExprNode {
type: string;
value?: any;
position?: number;
arguments?: ExprNode[];
name?: string;
procedure?: ExprNode;
steps?: ExprNode[];
expressions?: ExprNode[];
stages?: ExprNode[];
lhs?: ExprNode | ExprNode[];
rhs?: ExprNode;
}
interface JsonataError {
code: string;
position: number;
token: string;
message: string;
}
interface Focus {
environment: Environment;
input: any;
}
interface Environment {
bind(name: string | symbol, value: any): void;
lookup(name: string | symbol): any;
timestamp: Date;
async: boolean;
}