CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jsonata

JSON query and transformation language for extracting, filtering, and transforming JSON data

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

data-manipulation.mddocs/

Data Manipulation

Functions for transforming, filtering, and manipulating arrays and objects.

Capabilities

Array Transformation

Map Function

Applies a function to each element in an array, returning a new array.

/**
 * Apply function to each element in array
 * @param array - Input array
 * @param function - Function to apply to each element
 * @returns New array with transformed elements
 */
function $map(array, function);

Usage Examples:

// Transform array of numbers
const data = { numbers: [1, 2, 3, 4] };
const doubled = await jsonata('$map(numbers, function($item) { $item * 2 })').evaluate(data); // [2, 4, 6, 8]

// Transform objects
const users = { 
  users: [
    { name: "Alice", age: 30 },
    { name: "Bob", age: 25 }
  ]
};
const names = await jsonata('$map(users, function($user) { $user.name })').evaluate(users); // ["Alice", "Bob"]

// Using lambda syntax
const prices = { items: [{ price: 10 }, { price: 20 }] };
const withTax = await jsonata('$map(items, λ($item) { {"price": $item.price * 1.1} })').evaluate(prices);

Filter Function

Filters array elements based on a predicate function.

/**
 * Filter array elements using predicate function
 * @param array - Input array
 * @param function - Predicate function returning boolean
 * @returns Array containing only elements that pass the predicate
 */
function $filter(array, function);

Usage Examples:

// Filter numbers
const data = { numbers: [1, 2, 3, 4, 5, 6] };
const evens = await jsonata('$filter(numbers, function($n) { $n % 2 = 0 })').evaluate(data); // [2, 4, 6]

// Filter objects
const products = {
  products: [
    { name: "Laptop", price: 1000, inStock: true },
    { name: "Mouse", price: 25, inStock: false },
    { name: "Keyboard", price: 75, inStock: true }
  ]
};
const available = await jsonata('$filter(products, function($p) { $p.inStock })').evaluate(products);
// [{ name: "Laptop", price: 1000, inStock: true }, { name: "Keyboard", price: 75, inStock: true }]

// Filter with multiple conditions
const expensive = await jsonata('$filter(products, function($p) { $p.price > 50 and $p.inStock })').evaluate(products);

Zip Function

Combines multiple arrays element-wise into a single array.

/**
 * Combine multiple arrays element-wise
 * @param arrays - Multiple arrays to combine
 * @returns Array of arrays, each containing elements from the same position
 */
function $zip(...arrays);

Usage Examples:

const data = {
  names: ["Alice", "Bob", "Charlie"],
  ages: [30, 25, 35],
  cities: ["New York", "London", "Tokyo"]
};

const combined = await jsonata('$zip(names, ages, cities)').evaluate(data);
// [["Alice", 30, "New York"], ["Bob", 25, "London"], ["Charlie", 35, "Tokyo"]]

// Create objects from zipped arrays
const objects = await jsonata('$map($zip(names, ages), function($pair) { {"name": $pair[0], "age": $pair[1]} })').evaluate(data);
// [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]

Array Manipulation

Append Function

Appends arrays or values together.

/**
 * Append arrays or values
 * @param arg1 - First array or value
 * @param arg2 - Second array or value to append
 * @returns Combined array
 */
function $append(arg1, arg2);

Usage Examples:

const data = { 
  fruits: ["apple", "banana"],
  vegetables: ["carrot", "lettuce"]
};
const combined = await jsonata('$append(fruits, vegetables)').evaluate(data); 
// ["apple", "banana", "carrot", "lettuce"]

// Append single value
const withExtra = await jsonata('$append(fruits, "orange")').evaluate(data);
// ["apple", "banana", "orange"]

// Chain multiple appends
const all = await jsonata('$append($append(fruits, vegetables), ["bread", "milk"])').evaluate(data);

Reverse Function

Reverses the order of elements in an array.

/**
 * Reverse array elements
 * @param arr - Array to reverse
 * @returns New array with elements in reverse order
 */
function $reverse(arr);

Usage Examples:

const data = { items: [1, 2, 3, 4, 5] };
const reversed = await jsonata('$reverse(items)').evaluate(data); // [5, 4, 3, 2, 1]

// Reverse and process
const names = { list: ["Alice", "Bob", "Charlie"] };
const lastFirst = await jsonata('$reverse(list)[0]').evaluate(names); // "Charlie"

Sort Function

Sorts array elements using an optional comparison function.

/**
 * Sort array elements
 * @param arr - Array to sort
 * @param function - Optional comparison function
 * @returns New sorted array
 */
function $sort(arr, function);

Usage Examples:

// Sort numbers (default ascending)
const numbers = { values: [3, 1, 4, 1, 5, 9] };
const sorted = await jsonata('$sort(values)').evaluate(numbers); // [1, 1, 3, 4, 5, 9]

// Sort strings
const names = { list: ["Charlie", "Alice", "Bob"] };
const alphabetical = await jsonata('$sort(list)').evaluate(names); // ["Alice", "Bob", "Charlie"]

// Sort with custom function
const people = {
  people: [
    { name: "Alice", age: 30 },
    { name: "Charlie", age: 25 },
    { name: "Bob", age: 35 }
  ]
};
const byAge = await jsonata('$sort(people, function($a, $b) { $a.age < $b.age })').evaluate(people);
// Sorted by age ascending

// Sort by multiple criteria
const byNameThenAge = await jsonata('$sort(people, function($a, $b) { $a.name < $b.name ? true : $a.name > $b.name ? false : $a.age < $b.age })').evaluate(people);

Shuffle Function

Randomly shuffles array elements.

/**
 * Randomly shuffle array elements
 * @param arr - Array to shuffle
 * @returns New array with elements in random order
 */
function $shuffle(arr);

Distinct Function

Returns array with duplicate elements removed.

/**
 * Remove duplicate elements from array
 * @param arr - Array to process
 * @returns New array with unique elements only
 */
function $distinct(arr);

Usage Examples:

const data = { values: [1, 2, 2, 3, 3, 3, 4] };
const unique = await jsonata('$distinct(values)').evaluate(data); // [1, 2, 3, 4]

// Remove duplicate objects (by reference)
const items = {
  list: [
    { id: 1, name: "Apple" },
    { id: 2, name: "Banana" },
    { id: 1, name: "Apple" }
  ]
};
// Note: Objects are compared by deep equality
const distinctItems = await jsonata('$distinct(list)').evaluate(items);

Advanced Array Operations

Single Function

Returns a single element from an array, with optional filtering.

/**
 * Return single element from array
 * @param array - Input array
 * @param function - Optional filter function
 * @returns Single element, throws error if multiple or zero results
 */
function $single(array, function);

Usage Examples:

// Get single element (throws if not exactly one)
const data = { users: [{ name: "Alice", id: 1 }] };
const user = await jsonata('$single(users)').evaluate(data); // { name: "Alice", id: 1 }

// Get single matching element
const people = {
  people: [
    { name: "Alice", id: 1 },
    { name: "Bob", id: 2 },
    { name: "Charlie", id: 3 }
  ]
};
const alice = await jsonata('$single(people, function($p) { $p.name = "Alice" })').evaluate(people);

Fold Left Function

Reduces array from left using an accumulator function.

/**
 * Reduce array from left with accumulator function
 * @param array - Input array
 * @param function - Reducer function taking (accumulator, current, index, array)
 * @param init - Initial accumulator value
 * @returns Final accumulated result
 */
function $foldLeft(array, function, init);

Usage Examples:

// Sum with fold
const numbers = { values: [1, 2, 3, 4, 5] };
const sum = await jsonata('$foldLeft(values, function($acc, $val) { $acc + $val }, 0)').evaluate(numbers); // 15

// Build object from array
const items = { list: ["apple", "banana", "cherry"] };
const indexed = await jsonata('$foldLeft(list, function($acc, $val, $index) { $merge([$acc, {$string($index): $val}]) }, {})').evaluate(items);
// { "0": "apple", "1": "banana", "2": "cherry" }

// Find maximum with fold
const data = { values: [3, 7, 2, 9, 1] };
const max = await jsonata('$foldLeft(values, function($max, $val) { $val > $max ? $val : $max }, 0)').evaluate(data); // 9

Object Operations

Keys Function

Returns an array of object keys.

/**
 * Get object keys as array
 * @param arg - Object to get keys from
 * @returns Array of key strings
 */
function $keys(arg);

Usage Examples:

const user = { name: "Alice", age: 30, city: "New York" };
const keys = await jsonata('$keys($)').evaluate(user); // ["name", "age", "city"]

// Process each key-value pair
const obj = { a: 1, b: 2, c: 3 };
const pairs = await jsonata('$keys($).{"key": $, "value": $lookup($, $)}').evaluate(obj);
// [{"key": "a", "value": 1}, {"key": "b", "value": 2}, {"key": "c", "value": 3}]

Lookup Function

Looks up a value by key in an object.

/**
 * Look up value by key in object
 * @param input - Object to search in
 * @param key - Key to look up
 * @returns Value associated with the key
 */
function $lookup(input, key);

Usage Examples:

const data = { name: "Alice", age: 30 };
const name = await jsonata('$lookup($, "name")').evaluate(data); // "Alice"

// Dynamic key lookup
const config = { 
  settings: { theme: "dark", lang: "en" },
  currentSetting: "theme"
};
const value = await jsonata('$lookup(settings, currentSetting)').evaluate(config); // "dark"

Spread Function

Spreads an object into key-value pairs.

/**
 * Spread object into key-value pairs
 * @param arg - Object to spread
 * @returns Array of objects with "name" and "value" properties
 */
function $spread(arg);

Usage Examples:

const user = { name: "Alice", age: 30, city: "New York" };
const pairs = await jsonata('$spread($)').evaluate(user);
// [{"name": "name", "value": "Alice"}, {"name": "age", "value": 30}, {"name": "city", "value": "New York"}]

// Transform spread data
const transformed = await jsonata('$spread($).{"key": name, "val": $string(value)}').evaluate(user);

Merge Function

Merges an array of objects into a single object.

/**
 * Merge array of objects into single object
 * @param arg - Array of objects to merge
 * @returns Single merged object
 */
function $merge(arg);

Usage Examples:

const data = {
  objects: [
    { a: 1, b: 2 },
    { c: 3, d: 4 },
    { a: 10, e: 5 }  // 'a' will be overwritten
  ]
};
const merged = await jsonata('$merge(objects)').evaluate(data); // { a: 10, b: 2, c: 3, d: 4, e: 5 }

// Merge configuration objects
const config = {
  defaults: { theme: "light", timeout: 5000 },
  user: { theme: "dark" },
  runtime: { debug: true }
};
const final = await jsonata('$merge([defaults, user, runtime])').evaluate(config);
// { theme: "dark", timeout: 5000, debug: true }

Sift Function

Filters object properties using a predicate function.

/**
 * Filter object properties using predicate function
 * @param arg - Object to filter
 * @param func - Predicate function receiving (value, key, object)
 * @returns New object with filtered properties
 */
function $sift(arg, func);

Usage Examples:

// Filter by value
const data = { a: 1, b: 2, c: 3, d: 4, e: 5 };
const filtered = await jsonata('$sift($, function($value) { $value > 2 })').evaluate(data); // { c: 3, d: 4, e: 5 }

// Filter by key pattern
const config = {
  user_name: "Alice",
  user_age: 30,
  system_version: "1.0",
  system_debug: true
};
const userSettings = await jsonata('$sift($, function($value, $key) { $contains($key, "user_") })').evaluate(config);
// { user_name: "Alice", user_age: 30 }

Each Function

Applies a function to each property in an object.

/**
 * Apply function to each property in object
 * @param object - Object to iterate over
 * @param function - Function to apply to each property
 * @returns Array of results from function applications
 */
function $each(object, function);

Usage Examples:

const user = { name: "Alice", age: 30, city: "New York" };
const descriptions = await jsonata('$each($, function($value, $key) { $key & ": " & $string($value) })').evaluate(user);
// ["name: Alice", "age: 30", "city: New York"]

// Process nested objects
const data = {
  users: {
    alice: { age: 30, role: "admin" },
    bob: { age: 25, role: "user" }
  }
};
const summaries = await jsonata('$each(users, function($user, $name) { $name & " (" & $user.role & ")" })').evaluate(data);
// ["alice (admin)", "bob (user)"]

docs

data-manipulation.md

datetime-functions.md

expressions.md

index.md

numeric-functions.md

string-functions.md

utility-functions.md

tile.json