Jsonnet is a data templating language that extends JSON with variables, conditionals, functions, and imports for configuration management
—
The Jsonnet standard library provides 140+ built-in functions accessible via the std object. These functions cover string manipulation, array processing, object operations, mathematical computations, type checking, and data format serialization. All functions are automatically available in any Jsonnet program without requiring imports.
Functions for type checking and introspection.
// Get type name as string
std.type(x) // Returns "string", "number", "boolean", "array", "object", "function", or "null"
// Type checking predicates
std.isString(v) // Returns true if v is a string
std.isNumber(v) // Returns true if v is a number
std.isBoolean(v) // Returns true if v is a boolean
std.isObject(v) // Returns true if v is an object
std.isArray(v) // Returns true if v is an array
std.isFunction(v) // Returns true if v is a function
// Get length of arrays, strings, objects, or function arity
std.length(x) // Returns integer lengthComprehensive string manipulation and processing functions.
// Basic string operations
std.toString(a) // Convert value to string representation
std.substr(str, from, len) // Extract substring starting at from with length len
std.startsWith(a, b) // Returns true if string a starts with b
std.endsWith(a, b) // Returns true if string a ends with b
// Case conversion
std.asciiLower(str) // Convert ASCII characters to lowercase
std.asciiUpper(str) // Convert ASCII characters to uppercase
// String splitting and joining
std.split(str, c) // Split string on delimiter c
std.splitLimit(str, c, maxsplits) // Split string with maximum number of splits
std.splitLimitR(str, c, maxsplits) // Right-limited string split
std.join(sep, arr) // Join array elements with separator
// String trimming and cleaning
std.lstripChars(str, chars) // Strip characters from left of string
std.rstripChars(str, chars) // Strip characters from right of string
std.stripChars(str, chars) // Strip characters from both ends
std.trim(str) // Strip whitespace from both ends
// Character operations
std.stringChars(str) // Convert string to array of characters
std.codepoint(str) // Get Unicode code point of single character
std.char(n) // Get single character from Unicode code point
// String replacement and formatting
std.strReplace(str, from, to) // Replace all occurrences of from with to
std.format(str, vals) // Printf-style string formatting
// String parsing
std.parseInt(str) // Parse decimal integer from string
std.parseOctal(str) // Parse octal integer from string
std.parseHex(str) // Parse hexadecimal integer from string
// String escaping for various formats
std.escapeStringJson(str) // Escape string for JSON
std.escapeStringPython(str) // Escape string for Python
std.escapeStringBash(str) // Escape string for Bash
std.escapeStringDollars(str) // Escape dollar signs
std.escapeStringXML(str) // Escape string for XMLFunctions for array creation, manipulation, and processing.
// Array creation
std.makeArray(sz, func) // Create array of size sz by calling func for each index
std.range(from, to) // Create array of integers from from to to (inclusive)
std.repeat(what, count) // Repeat string or array count times
// Array access and slicing
std.slice(indexable, index, end, step) // Array/string slicing with optional step
std.member(arr, x) // Test if array/string contains element
std.count(arr, x) // Count occurrences of element
std.find(value, arr) // Find indices of value in array
std.contains(arr, elem) // Test if array contains element
// Array modification
std.reverse(arr) // Reverse array
std.sort(arr, keyF=id) // Sort array with optional key function
std.uniq(arr, keyF=id) // Remove duplicates from sorted array
std.flattenArrays(arrs) // Flatten array of arrays
std.flattenDeepArray(value) // Recursively flatten nested arrays
std.removeAt(arr, at) // Remove element at index
std.remove(arr, elem) // Remove first occurrence of element
// Higher-order array functions
std.map(func, arr) // Map function over array/string
std.mapWithIndex(func, arr) // Map function with index parameter
std.filter(func, arr) // Filter array elements where func returns true
std.flatMap(func, arr) // Map function and flatten results
std.filterMap(filter_func, map_func, arr) // Filter then map
// Array reduction
std.foldl(func, arr, init) // Left fold over array
std.foldr(func, arr, init) // Right fold over array
// Array aggregation
std.sum(arr) // Sum of array elements
std.avg(arr) // Average of array elements
std.minArray(arr, keyF=id, onEmpty=error) // Minimum array element
std.maxArray(arr, keyF=id, onEmpty=error) // Maximum array element
std.all(arr) // Test if all array elements are true
std.any(arr) // Test if any array element is trueFunctions for object manipulation and introspection.
// Object field access
std.objectFields(o) // Get visible field names
std.objectFieldsAll(o) // Get all field names including hidden
std.objectHas(o, f) // Test if object has visible field
std.objectHasAll(o, f) // Test if object has field including hidden
std.objectHasEx(obj, f, inc_hidden) // Check if object has field with hidden option
// Object value access
std.objectValues(o) // Get visible field values
std.objectValuesAll(o) // Get all field values
std.objectKeysValues(o) // Get key-value pairs for visible fields
std.objectKeysValuesAll(o) // Get all key-value pairs
std.objectFieldsEx(obj, inc_hidden) // Get field names with hidden option
// Object manipulation
std.objectRemoveKey(obj, key) // Remove key from object
std.get(o, f, default=null, inc_hidden=true) // Safe field access with default
std.mergePatch(target, patch) // RFC 7386 JSON Merge Patch
// Object iteration
std.mapWithKey(func, obj) // Map function over object values with keyComprehensive mathematical operations and constants.
// Basic arithmetic
std.abs(n) // Absolute value
std.sign(n) // Sign of number (-1, 0, or 1)
std.max(a, b) // Maximum of two numbers
std.min(a, b) // Minimum of two numbers
std.clamp(x, minVal, maxVal) // Clamp value to range
std.round(x) // Round to nearest integer
std.mod(a, b) // Modulo operation
std.modulo(a, b) // Modulo operation (alias)
// Trigonometric functions
std.sin(x) // Sine
std.cos(x) // Cosine
std.tan(x) // Tangent
std.asin(x) // Arc sine
std.acos(x) // Arc cosine
std.atan(x) // Arc tangent
std.atan2(y, x) // Arc tangent of y/x
// Exponential and logarithmic
std.pow(x, n) // x raised to power n
std.sqrt(x) // Square root
std.log(n) // Natural logarithm
std.log2(x) // Base-2 logarithm
std.log10(x) // Base-10 logarithm
std.exp(n) // e raised to power n
// Rounding and precision
std.floor(x) // Floor of number
std.ceil(x) // Ceiling of number
std.mantissa(n) // Mantissa of floating point number
std.exponent(n) // Exponent of floating point number
// Advanced math
std.hypot(a, b) // sqrt(a² + b²)
// Math constants
std.pi // Pi constant (3.14159...)
// Angle conversion
std.deg2rad(x) // Convert degrees to radians
std.rad2deg(x) // Convert radians to degreesFunctions for treating arrays as mathematical sets.
std.set(arr, keyF=id) // Convert array to sorted unique set
std.setMember(x, arr, keyF=id) // Test set membership
std.setUnion(a, b, keyF=id) // Set union
std.setInter(a, b, keyF=id) // Set intersection
std.setDiff(a, b, keyF=id) // Set differenceFunctions for serializing and parsing various data formats.
// JSON serialization
std.manifestJson(value) // Convert to JSON with default formatting
std.manifestJsonMinified(value) // Convert to minified JSON
std.manifestJsonEx(value, indent, newline, key_val_sep) // Customizable JSON output
// JSON parsing
std.parseJson(str) // Parse JSON string to Jsonnet value
// YAML serialization
std.manifestYamlDoc(value, indent_array_in_object=false, quote_keys=true) // YAML document
std.manifestYamlStream(value, indent_array_in_object=false, quote_keys=true) // YAML stream format
// YAML parsing
std.parseYaml(str) // Parse YAML string to Jsonnet value
// Other formats
std.manifestPython(v) // Python representation
std.manifestPythonVars(conf) // Python variable assignments
std.manifestXmlJsonml(value) // XML from JsonML format
std.manifestIni(ini) // INI file format
std.manifestToml(value) // TOML format with default indent
std.manifestTomlEx(value, indent) // TOML with custom indentFunctions for encoding and decoding data.
// Base64 encoding/decoding
std.base64(input) // Base64 encode string or byte array
std.base64Decode(str) // Base64 decode to string
std.base64DecodeBytes(str) // Base64 decode to byte array
// UTF-8 encoding/decoding
std.encodeUTF8(str) // Encode string to UTF-8 byte array
std.decodeUTF8(arr) // Decode UTF-8 byte array to string
// Hashing
std.md5(str) // MD5 hash of string
// Note: SHA functions available in Go version only
// std.sha1(str), std.sha256(str), std.sha512(str), std.sha3(str)General-purpose utility functions for common operations.
// Data processing
std.prune(a) // Remove empty arrays and objects
std.equals(a, b) // Deep equality comparison
std.deepJoin(arr) // Recursively join nested string arrays
std.lines(arr) // Join array with newlines
// Assertions and debugging
std.assertEqual(a, b) // Assertion function
std.trace(str, rest) // Print trace message and return rest
// Path operations
std.resolvePath(f, r) // Path resolution utility
// String utilities
std.findSubstr(pat, str) // Find substring positions
std.isEmpty(str) // Test if string is empty
std.equalsIgnoreCase(str1, str2) // Case-insensitive string comparison
// Number utilities
std.isEven(x) // Test if number is even
std.isOdd(x) // Test if number is odd
std.isInteger(x) // Test if number is integer
std.isDecimal(x) // Test if number is decimal
// Logical operations
std.xor(x, y) // Exclusive or
std.xnor(x, y) // Exclusive nor
// Comparison utilities
std.primitiveEquals(a, b) // Primitive equality comparisonFunctions for accessing external data and functionality.
std.extVar(x) // Access external variables set via -V or ext_vars
std.native(name) // Access native callback functions registered from host languageString manipulation:
{
original: " Hello World! ",
trimmed: std.trim(self.original),
upper: std.asciiUpper(self.trimmed),
parts: std.split(self.trimmed, " "),
rejoined: std.join("-", self.parts),
replaced: std.strReplace(self.original, "World", "Jsonnet")
}Array processing:
local numbers = [1, 2, 3, 4, 5];
{
doubled: std.map(function(x) x * 2, numbers),
evens: std.filter(function(x) x % 2 == 0, numbers),
sum: std.sum(numbers),
sorted_desc: std.sort(numbers, function(x) -x),
unique_items: std.uniq(std.sort([1, 2, 2, 3, 1, 4]))
}Object manipulation:
local config = {
name: "app",
version: "1.0",
debug:: true, // hidden field
port: 8080
};
{
fields: std.objectFields(config),
all_fields: std.objectFieldsAll(config),
has_debug: std.objectHasAll(config, "debug"),
config_pairs: std.objectKeysValues(config),
without_port: std.objectRemoveKey(config, "port")
}Mathematical operations:
{
calculations: {
sqrt_of_16: std.sqrt(16),
sin_pi_half: std.sin(std.pi / 2),
log_base_2: std.log(8) / std.log(2),
clamped: std.clamp(15, 0, 10),
rounded: std.round(3.7)
},
angle_conversion: {
degrees_to_rad: std.deg2rad(90),
radians_to_deg: std.rad2deg(std.pi)
}
}Data format conversion:
local data = { users: [{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }] };
{
json_minified: std.manifestJsonMinified(data),
yaml_format: std.manifestYamlDoc(data),
python_format: std.manifestPython(data.users),
ini_format: std.manifestIni({
section1: { key1: "value1", key2: "value2" },
section2: { key3: "value3" }
})
}Working with external variables:
// Use with: jsonnet -V environment=production -V debug=false config.jsonnet
{
environment: std.extVar("environment"),
debug_mode: std.extVar("debug") == "true",
log_level: if std.extVar("environment") == "production" then "warn" else "debug",
database_url: if std.extVar("environment") == "production"
then "prod-db.example.com"
else "dev-db.example.com"
}Set operations:
local set1 = ["a", "b", "c"];
local set2 = ["b", "c", "d"];
{
union: std.setUnion(set1, set2),
intersection: std.setInter(set1, set2),
difference: std.setDiff(set1, set2),
is_member: std.setMember("b", set1)
}Complex example with multiple functions:
local users = [
{ name: "Alice Johnson", email: "alice@example.com", age: 30, active: true },
{ name: "Bob Smith", email: "bob@example.com", age: 25, active: false },
{ name: "Charlie Brown", email: "charlie@example.com", age: 35, active: true }
];
{
// Process user data
active_users: std.filter(function(user) user.active, users),
// Transform and format
user_summary: std.map(function(user) {
name: user.name,
initials: std.join("", std.map(
function(part) part[0],
std.split(user.name, " ")
)),
contact: std.format("<%s>", user.email),
age_group: if user.age < 30 then "young" else "experienced"
}, self.active_users),
// Statistics
stats: {
total_users: std.length(users),
active_count: std.length(self.active_users),
average_age: std.round(
std.sum(std.map(function(user) user.age, users)) / std.length(users)
),
all_emails: std.join(", ", std.map(function(user) user.email, users))
},
// Export formatted data
yaml_export: std.manifestYamlDoc({
users: self.user_summary,
generated_at: "2024-01-01T00:00:00Z"
})
}Install with Tessl CLI
npx tessl i tessl/pypi-jsonnet