Crate jmespath_extensions

Crate jmespath_extensions 

Source
Expand description

§JMESPath Extensions

A comprehensive collection of 150+ extension functions for JMESPath queries.

§Built on jmespath.rs

This crate extends the jmespath crate by @mtdowling, which provides the complete Rust implementation of the JMESPath specification. All spec-compliant parsing, evaluation, and the 26 built-in functions come from that foundational library—we simply add extra functions on top.

If you only need standard JMESPath functionality, use jmespath directly.

§Non-Standard Extension Warning

These functions are NOT part of the JMESPath specification.

Queries using these extension functions will NOT work in other JMESPath implementations (Python, JavaScript, Go, etc.). If you need portable queries, use only the 26 standard JMESPath built-in functions:

abs, avg, ceil, contains, ends_with, floor, join, keys, length, map, max, max_by, merge, min, min_by, not_null, reverse, sort, sort_by, starts_with, sum, to_array, to_number, to_string, type, values

These extensions are useful when:

  • You control both the query author and the runtime environment
  • You need functionality beyond standard JMESPath
  • Cross-implementation compatibility is not required

§JEP Alignment

Some functions in this library align with JMESPath Enhancement Proposals (JEPs), which are draft specifications for extending JMESPath. While JEPs are not yet part of the official specification, aligning with them improves compatibility with other implementations that adopt the same proposals.

§JEP-013: Object Manipulation Functions

The following functions implement JEP-013:

FunctionSignatureDescription
itemsitems(object) → array[array]Returns [[key, value], ...] pairs
from_itemsfrom_items(array) → objectConverts [[key, value], ...] to object
zipzip(array1, array2) → arrayZips two arrays into pairs

§JEP-014: String Functions

The following functions implement JEP-014:

FunctionSignatureDescription
find_firstfind_first(string, sub, start?, end?) → number|nullFind first occurrence
find_lastfind_last(string, sub, start?, end?) → number|nullFind last occurrence
lowerlower(string) → stringConvert to lowercase
upperupper(string) → stringConvert to uppercase
trimtrim(string, chars?) → stringRemove leading/trailing chars
trim_lefttrim_left(string, chars?) → stringRemove leading chars
trim_righttrim_right(string, chars?) → stringRemove trailing chars
pad_leftpad_left(string, width, pad?) → stringLeft-pad to width
pad_rightpad_right(string, width, pad?) → stringRight-pad to width
replacereplace(string, old, new, count?) → stringReplace occurrences
splitsplit(string, sep, count?) → arraySplit into array

Note: Some JEP-014 functions in this library have slight signature differences (e.g., required vs optional parameters). See individual function documentation for details.

§Quick Start

use jmespath::{Runtime, Variable};
use jmespath_extensions::register_all;

// Create a runtime and register all extension functions
let mut runtime = Runtime::new();
runtime.register_builtin_functions();
register_all(&mut runtime);

// Use string functions
let expr = runtime.compile("upper(@)").unwrap();
let data = Variable::String("hello".to_string());
let result = expr.search(&data).unwrap();
assert_eq!(result.as_string().unwrap(), "HELLO");

§Working with JSON Data

Most real-world usage involves querying JSON data:

use jmespath::{Runtime, Variable};
use jmespath_extensions::register_all;

let mut runtime = Runtime::new();
runtime.register_builtin_functions();
register_all(&mut runtime);

// Parse JSON data
let json = r#"{
    "users": [
        {"name": "alice", "email": "ALICE@EXAMPLE.COM"},
        {"name": "bob", "email": "BOB@EXAMPLE.COM"}
    ]
}"#;
let data = Variable::from_json(json).unwrap();

// Query with extension functions
let expr = runtime.compile("users[*].{name: upper(name), email: lower(email)}").unwrap();
let result = expr.search(&data).unwrap();

// Result: [{"name": "ALICE", "email": "alice@example.com"}, {"name": "BOB", "email": "bob@example.com"}]

§Feature Flags

This crate uses feature flags to control which functions are included. This allows you to minimize dependencies and binary size.

FeatureDependenciesDescription
full (default)allAll functions
corenoneString, array, object, math, type, utility, path
stringnoneString manipulation
arraynoneArray operations
objectnoneObject utilities
mathnoneMathematical operations
typenoneType conversion and checking
utilitynoneUtility functions
pathnonePath manipulation
validationnoneValidation functions
hashmd-5, sha1, sha2, crc32fastHash functions
encodingbase64, hexEncoding functions
urlurlURL functions
regexregexRegex functions
uuiduuidUUID generation
randrandRandom functions
datetimechronoDate/time functions
fuzzystrsimFuzzy matching functions
expressionnoneExpression-based functions
phoneticrphoneticPhonetic encoding functions
geogeoutilsGeospatial functions
semversemverSemantic versioning
networkipnetworkNetwork/IP functions
idsnanoid, ulidID generation
textnoneText analysis
durationnoneDuration parsing
colornoneColor manipulation
computingnoneComputing utilities
jsonpatchjson-patchJSON Patch functions
multi-matchaho-corasickMulti-pattern matching

§Using Specific Features

# Only include string and array functions (no external dependencies)
[dependencies]
jmespath_extensions = { version = "0.1", default-features = false, features = ["string", "array"] }

# Include core functions plus regex
[dependencies]
jmespath_extensions = { version = "0.1", default-features = false, features = ["core", "regex"] }

§Module Overview

See each module’s documentation for detailed function reference with examples:

  • string - String manipulation (upper, lower, split, replace, camel_case, etc.)
  • array - Array operations (first, last, unique, chunk, zip, range, etc.)
  • object - Object utilities (items, pick, omit, deep_merge, etc.)
  • math - Math operations (round, sqrt, pow, median, sin, cos, etc.)
  • type_conv - Type functions (type_of, is_string, is_empty, to_number, etc.)
  • utility - Utilities (default, if, coalesce, json_encode, etc.)
  • datetime - Date/time (now, now_millis, parse_date, format_date, date_add, date_diff)
  • fuzzy - Fuzzy matching (levenshtein, jaro_winkler, sorensen_dice, etc.)
  • expression - Expression functions (map_expr, filter_expr, any_expr, all_expr, find_expr, sort_by_expr)
  • path - Path functions (path_basename, path_dirname, path_ext, path_join)
  • validation - Validation (is_email, is_url, is_uuid, is_ipv4, is_ipv6)
  • hash - Hashing (md5, sha1, sha256, crc32)
  • encoding - Encoding (base64_encode, base64_decode, hex_encode, hex_decode)
  • url_fns - URL functions (url_encode, url_decode, url_parse)
  • regex_fns - Regex (regex_match, regex_extract, regex_replace)
  • random - Random (random, shuffle, sample, uuid)
  • phonetic - Phonetic encoding (soundex, metaphone, double_metaphone, nysiis, sounds_like)
  • geo - Geospatial (haversine, haversine_km, haversine_mi, bearing)
  • semver_fns - Semantic versioning (semver_parse, semver_compare, semver_matches, is_semver)
  • network - Network/IP (ip_to_int, int_to_ip, cidr_contains, cidr_network, is_private_ip)
  • ids - ID generation (nanoid, ulid, ulid_timestamp)
  • text - Text analysis (word_count, char_count, reading_time, word_frequencies)
  • duration - Duration parsing (parse_duration, format_duration)
  • color - Color manipulation (hex_to_rgb, rgb_to_hex, lighten, darken, color_mix)
  • computing - Computing utilities (parse_bytes, format_bytes, bit_and, bit_or, bit_xor)
  • jsonpatch - JSON Patch (RFC 6902) and Merge Patch (RFC 7396) (json_patch, json_merge_patch, json_diff)

§Quick Reference (335 functions)

Click any function name to jump to its detailed documentation in the functions module.

§Array (array)

FunctionSignatureDescription
chunkarray, number -> arraySplit array into chunks of size n
compactarray -> arrayRemove null values from array
differencearray, array -> arrayElements in first array not in second
droparray, number -> arrayDrop first n elements
find_indexarray, any -> number | nullFind index of value in array
firstarray -> anyGet first element of array
flattenarray -> arrayFlatten array one level deep
flatten_deeparray -> arrayRecursively flatten nested arrays
frequenciesarray -> objectCount occurrences of each value
group_byarray, string -> objectGroup array elements by key
includesarray, any -> booleanCheck if array contains value
index_atarray, number -> anyGet element at index (supports negative)
intersectionarray, array -> arrayElements common to both arrays
lastarray -> anyGet last element of array
pairwisearray -> arrayReturn adjacent pairs from array
rangenumber, number -> arrayGenerate array of numbers
sliding_windowarray, number -> arrayCreate overlapping windows of size n (alias for window)
takearray, number -> arrayTake first n elements
transposearray -> arrayTranspose a 2D array (swap rows and columns)
unionarray, array -> arrayUnique elements from both arrays
uniquearray -> arrayRemove duplicate values
ziparray, array -> arrayZip two arrays together

§Color (color)

FunctionSignatureDescription
color_complementstring -> stringGet complementary color
color_grayscalestring -> stringConvert to grayscale
color_invertstring -> stringInvert a color
color_mixstring, string, number -> stringMix two colors
darkenstring, number -> stringDarken a color by percentage
hex_to_rgbstring -> objectConvert hex color to RGB
lightenstring, number -> stringLighten a color by percentage
rgb_to_hexnumber, number, number -> stringConvert RGB to hex color

§Computing (computing)

FunctionSignatureDescription
bit_andnumber, number -> numberBitwise AND
bit_notnumber -> numberBitwise NOT
bit_ornumber, number -> numberBitwise OR
bit_shift_leftnumber, number -> numberBitwise left shift
bit_shift_rightnumber, number -> numberBitwise right shift
bit_xornumber, number -> numberBitwise XOR
format_bytesnumber -> stringFormat bytes (decimal)
format_bytes_binarynumber -> stringFormat bytes (binary)
parse_bytesstring -> numberParse byte size string

§Datetime (datetime)

FunctionSignatureDescription
business_days_betweennumber, number -> numberCount business days (weekdays) between two timestamps
date_addnumber, number, string -> numberAdd time to timestamp
date_diffnumber, number, string -> numberDifference between timestamps
duration_sincenumber|string -> objectGet detailed duration object from timestamp to now
end_of_daynumber|string -> stringGet ISO 8601 string for end of day (23:59:59)
epoch_ms-> numberCurrent Unix timestamp in milliseconds (alias for now_ms)
format_datenumber, string -> stringFormat timestamp to string
from_epochnumber -> stringConvert Unix timestamp (seconds) to ISO 8601 string
from_epoch_msnumber -> stringConvert Unix timestamp (milliseconds) to ISO 8601 string
is_afternumber|string, number|string -> booleanCheck if first date is after second date (accepts timestamps or date strings)
is_beforenumber|string, number|string -> booleanCheck if first date is before second date (accepts timestamps or date strings)
is_betweennumber|string, number|string, number|string -> booleanCheck if date is between start and end (inclusive, accepts timestamps or date strings)
is_same_daynumber|string, number|string -> booleanCheck if two timestamps/dates are on the same day
is_weekdaynumber -> booleanCheck if timestamp falls on weekday (Monday-Friday)
is_weekendnumber -> booleanCheck if timestamp falls on weekend (Saturday or Sunday)
parse_datestring, string? -> numberParse date string to timestamp
quarternumber -> numberGet quarter of year (1-4) from timestamp
relative_timenumber -> stringHuman-readable relative time from timestamp
start_of_daynumber|string -> stringGet ISO 8601 string for start of day (00:00:00)
start_of_monthnumber|string -> stringGet ISO 8601 string for start of month
start_of_weeknumber|string -> stringGet ISO 8601 string for start of week (Monday 00:00:00)
start_of_yearnumber|string -> stringGet ISO 8601 string for start of year
time_agonumber|string -> stringHuman-readable time since date (accepts timestamps or date strings)
timezone_convertstring, string, string -> stringConvert timestamp between timezones (IANA timezone names)
to_epochnumber|string -> numberConvert date string or timestamp to Unix timestamp (seconds)
to_epoch_msnumber|string -> numberConvert date string or timestamp to Unix timestamp (milliseconds)

§Duration (duration)

FunctionSignatureDescription
duration_hoursnumber -> numberConvert seconds to hours
duration_minutesnumber -> numberConvert seconds to minutes
duration_secondsnumber -> numberGet seconds component
format_durationnumber -> stringFormat seconds as duration string
parse_durationstring -> numberParse duration string to seconds

§Encoding (encoding)

FunctionSignatureDescription
base64_decodestring -> stringDecode base64 string
base64_encodestring -> stringEncode string to base64
hex_decodestring -> stringDecode hex string
hex_encodestring -> stringEncode string to hex
jwt_decodestring -> objectDecode JWT payload (claims) without verification
jwt_headerstring -> objectDecode JWT header without verification
html_escapestring -> stringEscape HTML special characters
html_unescapestring -> stringUnescape HTML entities

§Expression (expression)

FunctionSignatureDescription
all_exprarray, expression -> booleanReturn true if every element satisfies the expression (short-circuits on false)
any_exprarray, expression -> booleanReturn true if any element satisfies the expression (short-circuits)
applyobject|string, ...any -> anyApply a partial function or invoke a function by name with arguments
count_bystring, array -> objectCount occurrences grouped by expression result
count_exprarray, expression -> numberCount how many elements satisfy the expression
drop_whilestring, array -> arrayDrop elements from array while expression is truthy
everystring, array -> booleanCheck if all elements match (alias for all_expr)
filter_exprarray, expression -> arrayKeep elements where JMESPath expression evaluates to truthy value
find_exprarray, expression -> anyReturn first element where expression is truthy, or null if none match
find_index_exprarray, expression -> number | nullReturn zero-based index of first matching element, or -1 if none match
flat_map_exprarray, expression -> arrayApply expression to each element and flatten all results into one array
group_by_exprarray, expression -> objectGroup elements into object keyed by expression result
map_exprarray, expression -> arrayApply a JMESPath expression to each element, returning transformed array
map_keysstring, object -> objectTransform object keys using expression
map_valuesstring, object -> objectTransform object values using expression
max_by_exprarray, expression -> anyReturn element with largest expression result, or null for empty array
min_by_exprarray, expression -> anyReturn element with smallest expression result, or null for empty array
order_byarray, array[[string, string]] -> arraySort array by multiple fields with ascending/descending control
partialstring, ...any -> objectCreate a partial function with some arguments pre-filled
partition_exprarray, expression -> arraySplit array into [matches, non-matches] based on expression
reduce_exprstring, array, any -> anyReduce array to single value using accumulator expression
rejectstring, array -> arrayKeep elements where expression is falsy (inverse of filter_expr)
scan_exprstring, array, any -> arrayLike reduce but returns array of intermediate accumulator values
somestring, array -> booleanCheck if any element matches (alias for any_expr)
sort_by_exprarray, expression -> arraySort array by expression result in ascending order
take_whilestring, array -> arrayTake elements from array while expression is truthy
unique_by_exprarray, expression -> arrayRemove duplicates by expression result, keeping first occurrence
zip_withstring, array, array -> arrayZip two arrays with a custom combiner expression
walkstring, any -> anyRecursively apply expression to all components of a value (bottom-up)

§Format (format)

FunctionSignatureDescription
to_csvarray -> stringConvert array to CSV row string (RFC 4180 compliant)
to_tsvarray -> stringConvert array to TSV row string (tab-separated)
to_csv_rowsarray -> stringConvert array of arrays to multi-line CSV string
to_csv_tablearray, array? -> stringConvert array of objects to CSV with header row

§Fuzzy (fuzzy)

FunctionSignatureDescription
damerau_levenshteinstring, string -> numberDamerau-Levenshtein distance
jarostring, string -> numberJaro similarity (0-1)
jaro_winklerstring, string -> numberJaro-Winkler similarity (0-1)
levenshteinstring, string -> numberLevenshtein edit distance
normalized_levenshteinstring, string -> numberNormalized Levenshtein (0-1)
sorensen_dicestring, string -> numberSorensen-Dice coefficient (0-1)

§Geo (geo)

FunctionSignatureDescription
geo_bearingnumber, number, number, number -> numberBearing between coordinates
geo_distancenumber, number, number, number -> numberHaversine distance in meters
geo_distance_kmnumber, number, number, number -> numberHaversine distance in kilometers
geo_distance_milesnumber, number, number, number -> numberHaversine distance in miles

§Hash (hash)

FunctionSignatureDescription
crc32string -> numberCalculate CRC32 checksum
hmac_md5string, string -> stringCalculate HMAC-MD5 signature
hmac_sha1string, string -> stringCalculate HMAC-SHA1 signature
hmac_sha256string, string -> stringCalculate HMAC-SHA256 signature
hmac_sha512string, string -> stringCalculate HMAC-SHA512 signature
md5string -> stringCalculate MD5 hash
sha1string -> stringCalculate SHA-1 hash
sha256string -> stringCalculate SHA-256 hash
sha512string -> stringCalculate SHA-512 hash

§Ids (ids)

FunctionSignatureDescription
nanoidnumber? -> stringGenerate nanoid
ulid-> stringGenerate ULID
ulid_timestampstring -> numberExtract timestamp from ULID

§JSON Patch (jsonpatch)

FunctionSignatureDescription
json_diffobject, object -> arrayGenerate JSON Patch (RFC 6902) that transforms first object into second
json_merge_patchobject, object -> objectApply JSON Merge Patch (RFC 7396) to an object
json_patchobject, array -> objectApply JSON Patch (RFC 6902) operations to an object

§Math (math)

FunctionSignatureDescription
abs_fnnumber -> numberAbsolute value
addnumber, number -> numberAdd two numbers
ceil_fnnumber -> numberRound up to nearest integer
clampnumber, number, number -> numberClamp value to range
cosnumber -> numberCosine function
covariancearray, array -> numberCovariance between two arrays
dividenumber, number -> numberDivide first number by second
ewmaarray, number -> arrayExponential weighted moving average
floor_fnnumber -> numberRound down to nearest integer
format_numbernumber, number?, string? -> stringFormat number with separators and optional suffix
lognumber -> numberNatural logarithm
medianarray -> numberCalculate median of array
mod_fnnumber, number -> numberModulo operation
modearray -> anyFind the most common value in an array
moving_avgarray, number -> arraySimple moving average with window size
multiplynumber, number -> numberMultiply two numbers
percentilearray, number -> numberCalculate percentile of array
pownumber, number -> numberRaise to power
quantilearray, number -> numberNth quantile (generalized percentile, q in [0,1])
roundnumber, number -> numberRound to specified decimal places
sinnumber -> numberSine function
sqrtnumber -> numberSquare root
standardizearray -> arrayStandardize array to mean=0, std=1 (z-score normalization)
stddevarray -> numberCalculate standard deviation of array
subtractnumber, number -> numberSubtract second number from first
tannumber -> numberTangent function
to_fixednumber, number -> stringFormat number with exact decimal places
variancearray -> numberCalculate variance of array

§Multimatch (multi_match)

FunctionSignatureDescription
extract_allstring, array[string] -> array[object]Extract all pattern matches with positions (Aho-Corasick)
extract_betweenstring, string, string -> string|nullExtract text between two delimiters
match_allstring, array[string] -> booleanCheck if string contains all of the patterns (Aho-Corasick)
match_anystring, array[string] -> booleanCheck if string contains any of the patterns (Aho-Corasick)
match_countstring, array[string] -> numberCount total pattern matches in string (Aho-Corasick)
match_positionsstring, array[string] -> array[object]Get start/end positions of all pattern matches (Aho-Corasick)
match_whichstring, array[string] -> array[string]Return array of patterns that match the string (Aho-Corasick)
replace_manystring, object -> stringReplace multiple patterns simultaneously (Aho-Corasick)
split_keepstring, string -> array[string]Split string keeping delimiters in result
tokenizestring, object? -> array[string]Smart word tokenization with optional lowercase and min_length

§Network (network)

FunctionSignatureDescription
cidr_broadcaststring -> stringGet broadcast address from CIDR
cidr_containsstring, string -> booleanCheck if IP is in CIDR range
cidr_networkstring -> stringGet network address from CIDR
cidr_prefixstring -> numberGet prefix length from CIDR
int_to_ipnumber -> stringConvert integer to IP address
ip_to_intstring -> numberConvert IP address to integer
is_private_ipstring -> booleanCheck if IP is in private range

§Object (object)

FunctionSignatureDescription
deep_diffobject, object -> objectStructural diff between two objects
deep_equalsany, any -> booleanDeep equality check for any two values
deep_mergeobject, object -> objectRecursively merge objects
defaultsobject, object -> objectAssign default values for missing keys (shallow)
defaults_deepobject, object -> objectRecursively assign default values for missing keys
delete_pathany, string -> anyDelete value at JSON pointer path (immutable)
flatten_keysobject -> objectFlatten nested object with dot notation keys
from_itemsarray -> objectConvert array of [key, value] pairs to object
getany, string, any? -> anyGet value at dot-separated path with optional default
hasany, string -> booleanCheck if dot-separated path exists
invertobject -> objectSwap keys and values
itemsobject -> arrayConvert object to array of [key, value] pairs
leavesany -> arrayGet all leaf values (non-object, non-array)
leaves_with_pathsany -> arrayGet all leaf values with their JSON pointer paths
omitobject, array -> objectRemove specific keys from object
pathsany -> arrayList all JSON pointer paths in value
pickobject, array -> objectSelect specific keys from object
rename_keysobject, object -> objectRename object keys
set_pathany, string, any -> anySet value at JSON pointer path (immutable)

§Path (path)

FunctionSignatureDescription
path_basenamestring -> stringGet filename from path
path_dirnamestring -> stringGet directory from path
path_extstring -> stringGet file extension
path_joinstring... -> stringJoin path segments

§Phonetic (phonetic)

FunctionSignatureDescription
caverphonestring -> stringCaverphone code
caverphone2string -> stringCaverphone 2 code
double_metaphonestring -> objectDouble Metaphone codes
match_rating_codexstring -> stringMatch Rating codex
metaphonestring -> stringMetaphone phonetic code
nysiisstring -> stringNYSIIS phonetic code
phonetic_matchstring, string, string -> booleanCheck phonetic match with algorithm
soundexstring -> stringSoundex phonetic code
sounds_likestring, string -> booleanCheck if strings sound similar

§Rand (rand)

FunctionSignatureDescription
random-> numberGenerate random number between 0 and 1
samplearray, number -> arrayRandom sample from array
shufflearray -> arrayRandomly shuffle array

§Regex (regex_fns)

FunctionSignatureDescription
regex_extractstring, string -> arrayExtract regex matches
regex_matchstring, string -> booleanTest if string matches regex
regex_replacestring, string, string -> stringReplace regex matches

§Semver (semver_fns)

FunctionSignatureDescription
semver_comparestring, string -> numberCompare versions (-1, 0, 1)
semver_is_validstring -> booleanCheck if string is valid semver
semver_majorstring -> numberGet major version
semver_minorstring -> numberGet minor version
semver_parsestring -> objectParse semantic version
semver_patchstring -> numberGet patch version
semver_satisfiesstring, string -> booleanCheck if version matches constraint

§Standard JMESPath (functions)

FunctionSignatureDescription
absnumber -> numberReturns the absolute value of a number
avgarray[number] -> numberReturns the average of an array of numbers
ceilnumber -> numberReturns the smallest integer greater than or equal to the number
containsarray|string, any -> booleanReturns true if the subject contains the search value
ends_withstring, string -> booleanReturns true if the subject ends with the suffix
floornumber -> numberReturns the largest integer less than or equal to the number
joinstring, array[string] -> stringReturns array elements joined into a string with a separator
keysobject -> array[string]Returns an array of keys from an object
lengtharray|object|string -> numberReturns the length of an array, object, or string
mapexpression, array -> arrayApplies an expression to each element of an array
maxarray[number]|array[string] -> number|stringReturns the maximum value in an array
max_byarray, expression -> anyReturns the element with maximum value by expression
mergeobject... -> objectMerges objects into a single object
minarray[number]|array[string] -> number|stringReturns the minimum value in an array
min_byarray, expression -> anyReturns the element with minimum value by expression
not_nullany... -> anyReturns the first non-null argument
reversearray|string -> array|stringReverses an array or string
sortarray[number]|array[string] -> arraySorts an array of numbers or strings
sort_byarray, expression -> arraySorts an array by expression result
starts_withstring, string -> booleanReturns true if the subject starts with the prefix
sumarray[number] -> numberReturns the sum of an array of numbers
to_arrayany -> arrayConverts a value to an array
to_numberany -> numberConverts a value to a number
to_stringany -> stringConverts a value to a string
typeany -> stringReturns the type of a value as a string
valuesobject -> arrayReturns an array of values from an object

§String (string)

FunctionSignatureDescription
abbreviatestring, number, string? -> stringTruncate string with ellipsis suffix
camel_casestring -> stringConvert to camelCase
capitalizestring -> stringCapitalize the first character
centerstring, number, string? -> stringCenter-pad string to given width
concatstring... -> stringConcatenate strings
explodestring -> arrayConvert a string to an array of Unicode codepoints
find_firststring, string -> number | nullFind first occurrence of substring
find_laststring, string -> number | nullFind last occurrence of substring
indicesstring, string -> arrayFind all indices of substring occurrences
implodearray -> stringConvert an array of Unicode codepoints to a string
insidestring, string -> booleanCheck if search string is contained in string
is_blankstring -> booleanCheck if string is empty or whitespace-only
kebab_casestring -> stringConvert to kebab-case
lowerstring -> stringConvert string to lowercase
ltrimstrstring, string -> stringRemove prefix from string if present
maskstring, number?, string? -> stringMask string, keeping last N characters visible
normalize_whitespacestring -> stringCollapse multiple whitespace to single space
pad_leftstring, number, string -> stringPad string on the left to reach target length
pad_rightstring, number, string -> stringPad string on the right to reach target length
redactstring, string, string? -> stringRedact regex pattern matches with replacement
repeatstring, number -> stringRepeat a string n times
replacestring, string, string -> stringReplace occurrences of a substring
reverse_stringstring -> stringReverse a string
rtrimstrstring, string -> stringRemove suffix from string if present
slicestring, number, number -> stringExtract substring by start and end index
snake_casestring -> stringConvert to snake_case
splitstring, string -> arraySplit string by delimiter
sprintfstring, any... -> stringPrintf-style string formatting
substrstring, number, number -> stringExtract substring by start index and length
titlestring -> stringConvert to title case
trimstring -> stringRemove leading and trailing whitespace
trim_leftstring -> stringRemove leading whitespace
trim_rightstring -> stringRemove trailing whitespace
upperstring -> stringConvert string to uppercase
wrapstring, number -> stringWrap text to specified width

§Text (text)

FunctionSignatureDescription
char_countstring -> numberCount characters in text
char_frequenciesstring -> objectCount character frequencies
paragraph_countstring -> numberCount paragraphs in text
reading_timestring -> stringEstimate reading time
reading_time_secondsstring -> numberEstimate reading time in seconds
sentence_countstring -> numberCount sentences in text
word_countstring -> numberCount words in text
word_frequenciesstring -> objectCount word frequencies
ngramsstring, number, string? -> arrayGenerate n-grams from text (word or character)
bigramsstring -> arrayGenerate word bigrams (2-grams)
trigramsstring -> arrayGenerate word trigrams (3-grams)

§Type (type_conv)

FunctionSignatureDescription
is_arrayany -> booleanCheck if value is an array
is_booleanany -> booleanCheck if value is a boolean
is_emptyany -> booleanCheck if value is empty
is_nullany -> booleanCheck if value is null
is_numberany -> booleanCheck if value is a number
is_objectany -> booleanCheck if value is an object
is_stringany -> booleanCheck if value is a string
to_booleanany -> booleanConvert value to boolean
type_ofany -> stringGet the type of a value

§Url (url_fns)

FunctionSignatureDescription
url_decodestring -> stringURL decode a string
url_encodestring -> stringURL encode a string
url_parsestring -> objectParse URL into components

§Utility (utility)

FunctionSignatureDescription
coalesceany... -> anyReturn first non-null value
defaultany, any -> anyReturn default value if null
ifboolean, any, any -> anyConditional expression
json_decodestring -> anyParse JSON string
json_encodeany -> stringSerialize value to JSON string
json_pointerany, string -> anyAccess value using JSON Pointer (RFC 6901)
now-> numberCurrent Unix timestamp in seconds
now_ms-> numberCurrent Unix timestamp in milliseconds
prettyany, number? -> stringPretty-print value as formatted JSON string
env-> objectGet all environment variables as an object
get_envstring -> string | nullGet a single environment variable by name

§Uuid (uuid)

FunctionSignatureDescription
uuid-> stringGenerate a UUID v4

§Validation (validation)

FunctionSignatureDescription
is_base64string -> booleanCheck if valid Base64 encoding
is_credit_cardstring -> booleanValidate credit card number (Luhn check + length)
is_emailstring -> booleanValidate email address format
is_hexstring -> booleanCheck if valid hexadecimal string
is_ipv4string -> booleanValidate IPv4 address format
is_ipv6string -> booleanValidate IPv6 address format
is_iso_datestring -> booleanValidate ISO 8601 date format
is_jsonstring -> booleanCheck if string is valid JSON
is_jwtstring -> booleanCheck if valid JWT structure (3 base64url parts)
is_phonestring -> booleanValidate phone number format
is_urlstring -> booleanValidate URL format
is_uuidstring -> booleanValidate UUID format
luhn_checkstring -> booleanGeneric Luhn algorithm check

§Error Handling

Extension functions follow JMESPath conventions:

  • Type errors return an error (e.g., passing a number to upper)
  • Invalid operations return null (e.g., index_at with out-of-bounds index)
use jmespath::{Runtime, Variable};
use jmespath_extensions::register_all;

let mut runtime = Runtime::new();
runtime.register_builtin_functions();
register_all(&mut runtime);

// Type error - upper expects a string
let expr = runtime.compile("upper(@)").unwrap();
let data = Variable::Number(serde_json::Number::from(42));
assert!(expr.search(&data).is_err());
// Out of bounds - returns null (requires "array" feature)
let expr = runtime.compile("index_at(@, `10`)").unwrap();
let data = Variable::from_json("[1, 2, 3]").unwrap();
let result = expr.search(&data).unwrap();
assert!(result.is_null());

Modules§

array
Array manipulation functions.
color
Color manipulation functions.
common
Common types and utilities for JMESPath extension functions.
computing
Computing and bitwise functions.
datetime
Date and time functions.
duration
Duration parsing and formatting functions.
encoding
Encoding and decoding functions.
expression
Expression-based higher-order functions.
format
CSV and TSV formatting functions.
functions
Complete function reference - auto-generated from functions.toml
fuzzy
Fuzzy string matching functions.
geo
Geographic/geospatial functions.
hash
Cryptographic hash functions.
ids
ID generation functions (nanoid, ulid).
jsonpatch
JSON Patch (RFC 6902) functions.
math
Mathematical functions.
multi_match
Multi-pattern matching functions.
network
Network and IP address functions.
object
Object/map manipulation functions.
path
File path manipulation functions.
phonetic
Phonetic encoding functions.
random
Random value generation functions.
regex_fns
Regular expression functions.
registry
Function registry for runtime control and introspection.
semver_fns
Semantic versioning functions.
string
String manipulation functions.
text
Text analysis functions.
type_conv
Type checking and conversion functions.
url_fns
URL parsing and manipulation functions.
utility
Utility functions.
validation
Data validation functions.

Macros§

define_function
Helper macro for defining JMESPath custom functions.

Structs§

Context
Context object used for error reporting.
JmespathError
JMESPath error.
Runtime
Compiles JMESPath expressions.
Signature
Represents a function’s signature.

Enums§

ArgumentType
Function argument types used when validating.
ErrorReason
Error context to provide specific details about an error.
Variable
JMESPath variable.

Traits§

Function
Represents a JMESPath function.

Functions§

register_all
Register all available extension functions with a JMESPath runtime.

Type Aliases§

Rcvar
Rc reference counted JMESPath Variable.