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

string-functions.mddocs/

String Functions

Comprehensive string manipulation, formatting, and transformation functions.

Capabilities

String Conversion and Formatting

String Conversion

Converts a value to its string representation.

/**
 * Convert value to string representation
 * @param arg - Value to convert to string
 * @param prettify - Optional boolean to pretty-print JSON objects
 * @returns String representation of the value
 */
function $string(arg, prettify);

Usage Examples:

const result1 = await jsonata("$string(123)").evaluate({}); // "123"
const result2 = await jsonata("$string(true)").evaluate({}); // "true"

// Pretty-print JSON objects
const data = { user: { name: "Alice", age: 30 } };
const pretty = await jsonata("$string(user, true)").evaluate(data);
// "{\n  \"name\": \"Alice\",\n  \"age\": 30\n}"

// Convert array elements to strings
const numbers = { values: [1, 2, 3] };
const strings = await jsonata("values.$string($)").evaluate(numbers); // ["1", "2", "3"]

Length Function

Returns the length of a string or array.

/**
 * Get length of string or array
 * @param str - String or array input
 * @returns Length of the input
 */
function $length(str);

Usage Examples:

const result1 = await jsonata('$length("hello")').evaluate({}); // 5
const result2 = await jsonata("$length([1, 2, 3])").evaluate({}); // 3

// Check field lengths
const user = { name: "Alice", email: "alice@example.com" };
const lengths = await jsonata("{ 'name': $length(name), 'email': $length(email) }").evaluate(user);
// { "name": 5, "email": 17 }

String Extraction

Substring Function

Extracts a substring from a string.

/**
 * Extract substring from string
 * @param str - Source string
 * @param start - Starting position (0-based)
 * @param length - Optional length of substring
 * @returns Extracted substring
 */
function $substring(str, start, length);

Usage Examples:

const result1 = await jsonata('$substring("hello world", 0, 5)').evaluate({}); // "hello"
const result2 = await jsonata('$substring("hello world", 6)').evaluate({}); // "world"

// Extract file extension
const file = { filename: "document.pdf" };
const ext = await jsonata('$substring(filename, $length(filename) - 3)').evaluate(file); // "pdf"

Substring Before

Returns the substring before the first occurrence of specified characters.

/**
 * Get substring before first occurrence of characters
 * @param str - Source string
 * @param chars - Characters to search for
 * @returns Substring before the characters, or original string if not found
 */
function $substringBefore(str, chars);

Usage Examples:

const result = await jsonata('$substringBefore("hello@world.com", "@")').evaluate({}); // "hello"

// Extract username from email
const user = { email: "john.doe@company.com" };
const username = await jsonata('$substringBefore(email, "@")').evaluate(user); // "john.doe"

Substring After

Returns the substring after the first occurrence of specified characters.

/**
 * Get substring after first occurrence of characters
 * @param str - Source string
 * @param chars - Characters to search for
 * @returns Substring after the characters, or empty string if not found
 */
function $substringAfter(str, chars);

Usage Examples:

const result = await jsonata('$substringAfter("hello@world.com", "@")').evaluate({}); // "world.com"

// Extract domain from email
const user = { email: "john.doe@company.com" };
const domain = await jsonata('$substringAfter(email, "@")').evaluate(user); // "company.com"

Case Conversion

Lowercase Function

Converts a string to lowercase.

/**
 * Convert string to lowercase
 * @param str - String to convert
 * @returns Lowercase version of the string
 */
function $lowercase(str);

Uppercase Function

Converts a string to uppercase.

/**
 * Convert string to uppercase
 * @param str - String to convert
 * @returns Uppercase version of the string
 */
function $uppercase(str);

Usage Examples:

const name = { firstName: "Alice", lastName: "Smith" };
const upper = await jsonata("$uppercase(firstName & ' ' & lastName)").evaluate(name); // "ALICE SMITH"
const lower = await jsonata("$lowercase(firstName & ' ' & lastName)").evaluate(name); // "alice smith"

// Normalize email addresses
const user = { email: "John.Doe@COMPANY.COM" };
const normalized = await jsonata("$lowercase(email)").evaluate(user); // "john.doe@company.com"

String Manipulation

Trim Function

Removes leading and trailing whitespace from a string.

/**
 * Remove leading and trailing whitespace
 * @param str - String to trim
 * @returns Trimmed string
 */
function $trim(str);

Usage Examples:

const result = await jsonata('$trim("  hello world  ")').evaluate({}); // "hello world"

// Clean user input
const form = { name: "  John Doe  ", email: "  john@example.com  " };
const cleaned = await jsonata("{ 'name': $trim(name), 'email': $trim(email) }").evaluate(form);
// { "name": "John Doe", "email": "john@example.com" }

Pad Function

Pads a string to a specified width with a character.

/**
 * Pad string to specified width
 * @param str - String to pad
 * @param width - Target width (negative for left padding, positive for right)
 * @param char - Optional padding character (defaults to space)
 * @returns Padded string
 */
function $pad(str, width, char);

Usage Examples:

const result1 = await jsonata('$pad("hello", 10)').evaluate({}); // "hello     "
const result2 = await jsonata('$pad("hello", -10)').evaluate({}); // "     hello"
const result3 = await jsonata('$pad("42", -5, "0")').evaluate({}); // "00042"

// Format table columns
const data = { items: [{ id: 1, name: "Apple" }, { id: 123, name: "Banana" }] };
const formatted = await jsonata('items.($pad($string(id), -4, "0") & " | " & name)').evaluate(data);
// ["0001 | Apple", "0123 | Banana"]

Pattern Matching and Processing

Split Function

Splits a string into an array using a separator.

/**
 * Split string into array using separator
 * @param str - String to split
 * @param separator - Separator string or regex pattern
 * @param limit - Optional maximum number of splits
 * @returns Array of string parts
 */
function $split(str, separator, limit);

Usage Examples:

const result1 = await jsonata('$split("apple,banana,cherry", ",")').evaluate({}); // ["apple", "banana", "cherry"]
const result2 = await jsonata('$split("one two three", " ", 2)').evaluate({}); // ["one", "two"]

// Parse CSV-like data
const csv = { line: "John,30,Manager,New York" };
const fields = await jsonata('$split(line, ",")').evaluate(csv); // ["John", "30", "Manager", "New York"]

// Split on multiple delimiters using regex
const text = { content: "apple;banana,cherry:grape" };
const fruits = await jsonata('$split(content, /[;,:]+/)').evaluate(text); // ["apple", "banana", "cherry", "grape"]

Join Function

Joins an array of strings into a single string using a separator.

/**
 * Join array elements into string with separator
 * @param strs - Array of strings to join
 * @param separator - Optional separator string (defaults to empty string)
 * @returns Joined string
 */
function $join(strs, separator);

Usage Examples:

const data = { words: ["hello", "world"] };
const result1 = await jsonata('$join(words, " ")').evaluate(data); // "hello world"
const result2 = await jsonata('$join(words, "-")').evaluate(data); // "hello-world"

// Create CSV line
const record = { fields: ["John Doe", "30", "Engineer"] };
const csv = await jsonata('$join(fields, ",")').evaluate(record); // "John Doe,30,Engineer"

// Build file path
const path = { parts: ["users", "documents", "file.txt"] };
const fullPath = await jsonata('$join(parts, "/")').evaluate(path); // "users/documents/file.txt"

Match Function

Matches a string against a regex pattern.

/**
 * Match string against regex pattern
 * @param str - String to match against
 * @param pattern - Regex pattern
 * @param limit - Optional maximum number of matches
 * @returns Array of match objects or null if no matches
 */
function $match(str, pattern, limit);

Usage Examples:

// Extract phone numbers
const text = { content: "Call me at 555-1234 or 555-5678" };
const phones = await jsonata('$match(content, /\\d{3}-\\d{4}/g)').evaluate(text);
// [{"match": "555-1234", "index": 11, "groups": []}, {"match": "555-5678", "index": 23, "groups": []}]

// Extract email addresses
const content = { text: "Contact john@example.com or mary@test.org" };
const emails = await jsonata('$match(text, /[\\w._%+-]+@[\\w.-]+\\.[A-Za-z]{2,}/g).match').evaluate(content);
// ["john@example.com", "mary@test.org"]

Contains Function

Tests if a string contains a pattern.

/**
 * Test if string contains pattern
 * @param str - String to test
 * @param pattern - Pattern to search for (string or regex)
 * @returns Boolean indicating if pattern was found
 */
function $contains(str, pattern);

Usage Examples:

const result1 = await jsonata('$contains("hello world", "world")').evaluate({}); // true
const result2 = await jsonata('$contains("hello world", "xyz")').evaluate({}); // false

// Filter array by content
const data = { emails: ["john@gmail.com", "mary@yahoo.com", "bob@company.com"] };
const gmailUsers = await jsonata('emails[$contains($, "gmail")]').evaluate(data); // ["john@gmail.com"]

// Case-insensitive search using regex
const text = { content: "Hello World" };
const hasHello = await jsonata('$contains(content, /hello/i)').evaluate(text); // true

Replace Function

Replaces occurrences of a pattern in a string with a replacement.

/**
 * Replace pattern in string with replacement
 * @param str - Source string
 * @param pattern - Pattern to replace (string or regex)
 * @param replacement - Replacement string
 * @param limit - Optional maximum number of replacements
 * @returns String with replacements made
 */
function $replace(str, pattern, replacement, limit);

Usage Examples:

const result1 = await jsonata('$replace("hello world", "world", "universe")').evaluate({}); // "hello universe"
const result2 = await jsonata('$replace("one two one", "one", "THREE", 1)').evaluate({}); // "THREE two one"

// Clean up whitespace
const text = { content: "hello    world   test" };
const cleaned = await jsonata('$replace(content, /\\s+/g, " ")').evaluate(text); // "hello world test"

// Mask sensitive data
const user = { ssn: "123-45-6789" };
const masked = await jsonata('$replace(ssn, /\\d(?=\\d{4})/g, "X")').evaluate(user); // "XXX-XX-6789"

docs

data-manipulation.md

datetime-functions.md

expressions.md

index.md

numeric-functions.md

string-functions.md

utility-functions.md

tile.json