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

utility-functions.mddocs/

Utility Functions

Encoding functions, type checking, and utility operations for JSONata expressions.

Capabilities

Encoding and Decoding Functions

Base64 Functions

Encode and decode strings using Base64 encoding.

/**
 * Encode string to Base64
 * @param str - String to encode
 * @returns Base64 encoded string
 */
function $base64encode(str);

/**
 * Decode Base64 string
 * @param str - Base64 encoded string to decode
 * @returns Decoded string
 */
function $base64decode(str);

Usage Examples:

// Basic encoding/decoding
const encoded = await jsonata('$base64encode("Hello World")').evaluate({}); // "SGVsbG8gV29ybGQ="
const decoded = await jsonata('$base64decode("SGVsbG8gV29ybGQ=")').evaluate({}); // "Hello World"

// Process user data
const user = { 
  username: "john.doe",
  password: "secret123"
};
const encoded_pass = await jsonata('{"username": username, "password": $base64encode(password)}').evaluate(user);

// Encode/decode arrays of strings
const data = { messages: ["Hello", "World", "JSONata"] };
const encoded_msgs = await jsonata('messages.$base64encode($)').evaluate(data);
const decoded_msgs = await jsonata('encoded_msgs.$base64decode($)').evaluate({ encoded_msgs });

URL Encoding Functions

Encode and decode URLs and URL components.

/**
 * Encode string for use in URL component
 * @param str - String to encode
 * @returns URL component encoded string
 */
function $encodeUrlComponent(str);

/**
 * Encode complete URL
 * @param str - URL string to encode
 * @returns URL encoded string
 */
function $encodeUrl(str);

/**
 * Decode URL component
 * @param str - URL component encoded string to decode
 * @returns Decoded string
 */
function $decodeUrlComponent(str);

/**
 * Decode complete URL
 * @param str - URL encoded string to decode
 * @returns Decoded URL string
 */
function $decodeUrl(str);

Usage Examples:

// URL component encoding for query parameters
const query = await jsonata('$encodeUrlComponent("hello world & more")').evaluate({}); // "hello%20world%20%26%20more"
const decoded = await jsonata('$decodeUrlComponent("hello%20world%20%26%20more")').evaluate({}); // "hello world & more"

// Build query string
const params = {
  search: "john doe",
  category: "users & admins",
  limit: "50"
};
const queryString = await jsonata('$keys($).($encodeUrlComponent($) & "=" & $encodeUrlComponent($lookup($$, $))).join("&")').evaluate(params);
// "search=john%20doe&category=users%20%26%20admins&limit=50"

// Process form data
const form = {
  fields: [
    { name: "full name", value: "John Doe Jr." },
    { name: "email", value: "john@example.com" },
    { name: "comment", value: "Hello & welcome!" }
  ]
};
const encoded_form = await jsonata('fields.{"name": $encodeUrlComponent(name), "value": $encodeUrlComponent(value)}').evaluate(form);

Type Checking and Conversion

Type Function

Returns the type of a value as a string.

/**
 * Get type of value
 * @param value - Value to check type of
 * @returns String representing the type
 */
function $type(value);

Usage Examples:

// Check types of various values
const types = await jsonata(`{
  "number": $type(42),
  "string": $type("hello"),
  "boolean": $type(true),
  "array": $type([1,2,3]),
  "object": $type({"key": "value"}),
  "null": $type(null)
}`).evaluate({});
// { number: "number", string: "string", boolean: "boolean", array: "array", object: "object", null: "null" }

// Filter by type
const mixed = { 
  values: [1, "hello", true, [1,2], {"a": 1}, null, 3.14]
};
const numbers = await jsonata('values[$type($) = "number"]').evaluate(mixed); // [1, 3.14]
const strings = await jsonata('values[$type($) = "string"]').evaluate(mixed); // ["hello"]

// Type-safe operations
const data = { input: "123" };
const processed = await jsonata(`
  $type(input) = "string" ? $number(input) : input
`).evaluate(data); // 123

Boolean Conversion

Converts a value to boolean according to JSONata truthiness rules.

/**
 * Convert value to boolean
 * @param arg - Value to convert
 * @returns Boolean representation of the value
 */
function $boolean(arg);

Usage Examples:

// Convert various values to boolean
const booleans = await jsonata(`{
  "number": $boolean(42),      // true
  "zero": $boolean(0),         // false
  "string": $boolean("hello"), // true
  "empty": $boolean(""),       // false
  "array": $boolean([1,2,3]),  // true
  "emptyArray": $boolean([]),  // false
  "object": $boolean({}),      // false
  "null": $boolean(null),      // false
  "undefined": $boolean(undefined) // false
}`).evaluate({});

// Conditional logic
const user = { name: "", email: "john@example.com" };
const hasName = await jsonata('$boolean(name)').evaluate(user); // false
const hasEmail = await jsonata('$boolean(email)').evaluate(user); // true

// Filter truthy values
const data = { values: [0, 1, "", "hello", [], [1], {}, {"a": 1}, null, false, true] };
const truthy = await jsonata('values[$boolean($)]').evaluate(data); // [1, "hello", [1], true]

Not Function

Returns the logical NOT of a value.

/**
 * Logical NOT operation
 * @param arg - Value to negate
 * @returns Boolean negation of the value
 */
function $not(arg);

Usage Examples:

// Basic NOT operations
const results = await jsonata(`{
  "true": $not(true),          // false
  "false": $not(false),        // true
  "truthy": $not("hello"),     // false
  "falsy": $not(""),           // true
  "number": $not(42),          // false
  "zero": $not(0)              // true
}`).evaluate({});

// Conditional logic
const user = { active: false, banned: true };
const canLogin = await jsonata('active and $not(banned)').evaluate(user); // false

// Filter using NOT
const items = {
  products: [
    { name: "Laptop", available: true },
    { name: "Mouse", available: false },
    { name: "Keyboard", available: true }
  ]
};
const unavailable = await jsonata('products[$not(available)]').evaluate(items);
// [{ name: "Mouse", available: false }]

Existence and Error Handling

Exists Function

Tests if a value exists (is not null or undefined).

/**
 * Test if value exists (not null/undefined)
 * @param arg - Value to test
 * @returns Boolean indicating if value exists
 */
function $exists(arg);

Usage Examples:

// Test existence of values
const data = {
  name: "John",
  age: null,
  email: undefined,
  active: false
};

const exists = await jsonata(`{
  "name": $exists(name),        // true
  "age": $exists(age),          // false
  "email": $exists(email),      // false
  "active": $exists(active),    // true
  "missing": $exists(missing)   // false
}`).evaluate(data);

// Filter existing values
const users = {
  users: [
    { name: "Alice", email: "alice@example.com" },
    { name: "Bob", email: null },
    { name: "Charlie" }
  ]
};
const withEmail = await jsonata('users[$exists(email)]').evaluate(users);
// [{ name: "Alice", email: "alice@example.com" }]

// Conditional processing
const profile = { name: "John", bio: "Developer" };
const display = await jsonata(`{
  "name": name,
  "bio": $exists(bio) ? bio : "No bio available"
}`).evaluate(profile);

Error Function

Throws an error with an optional message.

/**
 * Throw error with optional message
 * @param message - Optional error message
 * @throws Error with specified message
 */
function $error(message);

Usage Examples:

// Throw error with message
try {
  await jsonata('$error("Something went wrong")').evaluate({});
} catch (error) {
  console.log(error.message); // "Something went wrong"
}

// Conditional error throwing
const user = { age: -5 };
try {
  const result = await jsonata('age < 0 ? $error("Age cannot be negative") : age').evaluate(user);
} catch (error) {
  console.log(error.message); // "Age cannot be negative"
}

// Validation with errors
const data = { email: "invalid-email" };
const validation = jsonata(`
  $contains(email, "@") ? email : $error("Invalid email format")
`);

Assert Function

Asserts that a condition is true, throwing an error if false.

/**
 * Assert condition is true
 * @param condition - Condition to test
 * @param message - Optional error message if assertion fails
 * @throws Error if condition is false
 */
function $assert(condition, message);

Usage Examples:

// Basic assertions
const user = { name: "John", age: 30 };

// This passes
await jsonata('$assert($exists(name), "Name is required")').evaluate(user);

// This would throw
try {
  await jsonata('$assert(age > 50, "User must be over 50")').evaluate(user);
} catch (error) {
  console.log(error.message); // "User must be over 50"
}

// Multiple assertions
const data = { 
  users: [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" }
  ]
};

const validation = jsonata(`
  $assert($count(users) > 0, "Users array cannot be empty");
  $assert($all(users, function($u) { $exists($u.id) and $exists($u.name) }), "All users must have id and name");
  users
`);

// Use in data processing pipeline
const processUser = jsonata(`
  $assert($exists(email), "Email is required");
  $assert($contains(email, "@"), "Email must contain @");
  $assert($length(name) > 0, "Name cannot be empty");
  {
    "id": $uuid(),
    "name": name,
    "email": $lowercase(email)
  }
`);

Advanced Utility Patterns

Validation Patterns

// Email validation
const validateEmail = jsonata(`
  $assert($exists(email), "Email is required");
  $assert($type(email) = "string", "Email must be a string");
  $assert($contains(email, "@") and $contains(email, "."), "Invalid email format");
  email
`);

// Number range validation
const validateAge = jsonata(`
  $assert($exists(age), "Age is required");
  $assert($type(age) = "number", "Age must be a number");
  $assert(age >= 0 and age <= 150, "Age must be between 0 and 150");
  age
`);

// Array validation
const validateArray = jsonata(`
  $assert($type(data) = "array", "Data must be an array");
  $assert($count(data) > 0, "Array cannot be empty");
  $assert($all(data, function($item) { $type($item) = "number" }), "All items must be numbers");
  data
`);

Type-Safe Operations

// Safe string operations
const safeStringOp = jsonata(`
  $type(input) = "string" ? $uppercase(input) : $string(input)
`);

// Safe numeric operations
const safeNumericOp = jsonata(`
  $type(input) = "number" ? input * 2 : $number(input) * 2
`);

// Safe array operations
const safeArrayOp = jsonata(`
  $type(input) = "array" ? $count(input) : $count([input])
`);

Debugging Utilities

// Debug information
const debugInfo = jsonata(`{
  "type": $type($),
  "exists": $exists($),
  "boolean": $boolean($),
  "string": $string($),
  "length": $type($) = "array" or $type($) = "string" ? $length($) : null
}`);

// Conditional debugging
const conditionalDebug = jsonata(`
  debug = true ? 
    $merge([
      $,
      {"_debug": {"type": $type($), "processed_at": $now()}}
    ]) : 
    $
`);

docs

data-manipulation.md

datetime-functions.md

expressions.md

index.md

numeric-functions.md

string-functions.md

utility-functions.md

tile.json