0
# Standard Library
1
2
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.
3
4
## Capabilities
5
6
### Type System Functions
7
8
Functions for type checking and introspection.
9
10
```jsonnet { .api }
11
// Get type name as string
12
std.type(x) // Returns "string", "number", "boolean", "array", "object", "function", or "null"
13
14
// Type checking predicates
15
std.isString(v) // Returns true if v is a string
16
std.isNumber(v) // Returns true if v is a number
17
std.isBoolean(v) // Returns true if v is a boolean
18
std.isObject(v) // Returns true if v is an object
19
std.isArray(v) // Returns true if v is an array
20
std.isFunction(v) // Returns true if v is a function
21
22
// Get length of arrays, strings, objects, or function arity
23
std.length(x) // Returns integer length
24
```
25
26
### String Functions
27
28
Comprehensive string manipulation and processing functions.
29
30
```jsonnet { .api }
31
// Basic string operations
32
std.toString(a) // Convert value to string representation
33
std.substr(str, from, len) // Extract substring starting at from with length len
34
std.startsWith(a, b) // Returns true if string a starts with b
35
std.endsWith(a, b) // Returns true if string a ends with b
36
37
// Case conversion
38
std.asciiLower(str) // Convert ASCII characters to lowercase
39
std.asciiUpper(str) // Convert ASCII characters to uppercase
40
41
// String splitting and joining
42
std.split(str, c) // Split string on delimiter c
43
std.splitLimit(str, c, maxsplits) // Split string with maximum number of splits
44
std.splitLimitR(str, c, maxsplits) // Right-limited string split
45
std.join(sep, arr) // Join array elements with separator
46
47
// String trimming and cleaning
48
std.lstripChars(str, chars) // Strip characters from left of string
49
std.rstripChars(str, chars) // Strip characters from right of string
50
std.stripChars(str, chars) // Strip characters from both ends
51
std.trim(str) // Strip whitespace from both ends
52
53
// Character operations
54
std.stringChars(str) // Convert string to array of characters
55
std.codepoint(str) // Get Unicode code point of single character
56
std.char(n) // Get single character from Unicode code point
57
58
// String replacement and formatting
59
std.strReplace(str, from, to) // Replace all occurrences of from with to
60
std.format(str, vals) // Printf-style string formatting
61
62
// String parsing
63
std.parseInt(str) // Parse decimal integer from string
64
std.parseOctal(str) // Parse octal integer from string
65
std.parseHex(str) // Parse hexadecimal integer from string
66
67
// String escaping for various formats
68
std.escapeStringJson(str) // Escape string for JSON
69
std.escapeStringPython(str) // Escape string for Python
70
std.escapeStringBash(str) // Escape string for Bash
71
std.escapeStringDollars(str) // Escape dollar signs
72
std.escapeStringXML(str) // Escape string for XML
73
```
74
75
### Array Functions
76
77
Functions for array creation, manipulation, and processing.
78
79
```jsonnet { .api }
80
// Array creation
81
std.makeArray(sz, func) // Create array of size sz by calling func for each index
82
std.range(from, to) // Create array of integers from from to to (inclusive)
83
std.repeat(what, count) // Repeat string or array count times
84
85
// Array access and slicing
86
std.slice(indexable, index, end, step) // Array/string slicing with optional step
87
std.member(arr, x) // Test if array/string contains element
88
std.count(arr, x) // Count occurrences of element
89
std.find(value, arr) // Find indices of value in array
90
std.contains(arr, elem) // Test if array contains element
91
92
// Array modification
93
std.reverse(arr) // Reverse array
94
std.sort(arr, keyF=id) // Sort array with optional key function
95
std.uniq(arr, keyF=id) // Remove duplicates from sorted array
96
std.flattenArrays(arrs) // Flatten array of arrays
97
std.flattenDeepArray(value) // Recursively flatten nested arrays
98
std.removeAt(arr, at) // Remove element at index
99
std.remove(arr, elem) // Remove first occurrence of element
100
101
// Higher-order array functions
102
std.map(func, arr) // Map function over array/string
103
std.mapWithIndex(func, arr) // Map function with index parameter
104
std.filter(func, arr) // Filter array elements where func returns true
105
std.flatMap(func, arr) // Map function and flatten results
106
std.filterMap(filter_func, map_func, arr) // Filter then map
107
108
// Array reduction
109
std.foldl(func, arr, init) // Left fold over array
110
std.foldr(func, arr, init) // Right fold over array
111
112
// Array aggregation
113
std.sum(arr) // Sum of array elements
114
std.avg(arr) // Average of array elements
115
std.minArray(arr, keyF=id, onEmpty=error) // Minimum array element
116
std.maxArray(arr, keyF=id, onEmpty=error) // Maximum array element
117
std.all(arr) // Test if all array elements are true
118
std.any(arr) // Test if any array element is true
119
```
120
121
### Object Functions
122
123
Functions for object manipulation and introspection.
124
125
```jsonnet { .api }
126
// Object field access
127
std.objectFields(o) // Get visible field names
128
std.objectFieldsAll(o) // Get all field names including hidden
129
std.objectHas(o, f) // Test if object has visible field
130
std.objectHasAll(o, f) // Test if object has field including hidden
131
std.objectHasEx(obj, f, inc_hidden) // Check if object has field with hidden option
132
133
// Object value access
134
std.objectValues(o) // Get visible field values
135
std.objectValuesAll(o) // Get all field values
136
std.objectKeysValues(o) // Get key-value pairs for visible fields
137
std.objectKeysValuesAll(o) // Get all key-value pairs
138
std.objectFieldsEx(obj, inc_hidden) // Get field names with hidden option
139
140
// Object manipulation
141
std.objectRemoveKey(obj, key) // Remove key from object
142
std.get(o, f, default=null, inc_hidden=true) // Safe field access with default
143
std.mergePatch(target, patch) // RFC 7386 JSON Merge Patch
144
145
// Object iteration
146
std.mapWithKey(func, obj) // Map function over object values with key
147
```
148
149
### Mathematical Functions
150
151
Comprehensive mathematical operations and constants.
152
153
```jsonnet { .api }
154
// Basic arithmetic
155
std.abs(n) // Absolute value
156
std.sign(n) // Sign of number (-1, 0, or 1)
157
std.max(a, b) // Maximum of two numbers
158
std.min(a, b) // Minimum of two numbers
159
std.clamp(x, minVal, maxVal) // Clamp value to range
160
std.round(x) // Round to nearest integer
161
std.mod(a, b) // Modulo operation
162
std.modulo(a, b) // Modulo operation (alias)
163
164
// Trigonometric functions
165
std.sin(x) // Sine
166
std.cos(x) // Cosine
167
std.tan(x) // Tangent
168
std.asin(x) // Arc sine
169
std.acos(x) // Arc cosine
170
std.atan(x) // Arc tangent
171
std.atan2(y, x) // Arc tangent of y/x
172
173
// Exponential and logarithmic
174
std.pow(x, n) // x raised to power n
175
std.sqrt(x) // Square root
176
std.log(n) // Natural logarithm
177
std.log2(x) // Base-2 logarithm
178
std.log10(x) // Base-10 logarithm
179
std.exp(n) // e raised to power n
180
181
// Rounding and precision
182
std.floor(x) // Floor of number
183
std.ceil(x) // Ceiling of number
184
std.mantissa(n) // Mantissa of floating point number
185
std.exponent(n) // Exponent of floating point number
186
187
// Advanced math
188
std.hypot(a, b) // sqrt(a² + b²)
189
190
// Math constants
191
std.pi // Pi constant (3.14159...)
192
193
// Angle conversion
194
std.deg2rad(x) // Convert degrees to radians
195
std.rad2deg(x) // Convert radians to degrees
196
```
197
198
### Set Operations
199
200
Functions for treating arrays as mathematical sets.
201
202
```jsonnet { .api }
203
std.set(arr, keyF=id) // Convert array to sorted unique set
204
std.setMember(x, arr, keyF=id) // Test set membership
205
std.setUnion(a, b, keyF=id) // Set union
206
std.setInter(a, b, keyF=id) // Set intersection
207
std.setDiff(a, b, keyF=id) // Set difference
208
```
209
210
### Data Format Functions
211
212
Functions for serializing and parsing various data formats.
213
214
```jsonnet { .api }
215
// JSON serialization
216
std.manifestJson(value) // Convert to JSON with default formatting
217
std.manifestJsonMinified(value) // Convert to minified JSON
218
std.manifestJsonEx(value, indent, newline, key_val_sep) // Customizable JSON output
219
220
// JSON parsing
221
std.parseJson(str) // Parse JSON string to Jsonnet value
222
223
// YAML serialization
224
std.manifestYamlDoc(value, indent_array_in_object=false, quote_keys=true) // YAML document
225
std.manifestYamlStream(value, indent_array_in_object=false, quote_keys=true) // YAML stream format
226
227
// YAML parsing
228
std.parseYaml(str) // Parse YAML string to Jsonnet value
229
230
// Other formats
231
std.manifestPython(v) // Python representation
232
std.manifestPythonVars(conf) // Python variable assignments
233
std.manifestXmlJsonml(value) // XML from JsonML format
234
std.manifestIni(ini) // INI file format
235
std.manifestToml(value) // TOML format with default indent
236
std.manifestTomlEx(value, indent) // TOML with custom indent
237
```
238
239
### Encoding Functions
240
241
Functions for encoding and decoding data.
242
243
```jsonnet { .api }
244
// Base64 encoding/decoding
245
std.base64(input) // Base64 encode string or byte array
246
std.base64Decode(str) // Base64 decode to string
247
std.base64DecodeBytes(str) // Base64 decode to byte array
248
249
// UTF-8 encoding/decoding
250
std.encodeUTF8(str) // Encode string to UTF-8 byte array
251
std.decodeUTF8(arr) // Decode UTF-8 byte array to string
252
253
// Hashing
254
std.md5(str) // MD5 hash of string
255
256
// Note: SHA functions available in Go version only
257
// std.sha1(str), std.sha256(str), std.sha512(str), std.sha3(str)
258
```
259
260
### Utility Functions
261
262
General-purpose utility functions for common operations.
263
264
```jsonnet { .api }
265
// Data processing
266
std.prune(a) // Remove empty arrays and objects
267
std.equals(a, b) // Deep equality comparison
268
std.deepJoin(arr) // Recursively join nested string arrays
269
std.lines(arr) // Join array with newlines
270
271
// Assertions and debugging
272
std.assertEqual(a, b) // Assertion function
273
std.trace(str, rest) // Print trace message and return rest
274
275
// Path operations
276
std.resolvePath(f, r) // Path resolution utility
277
278
// String utilities
279
std.findSubstr(pat, str) // Find substring positions
280
std.isEmpty(str) // Test if string is empty
281
std.equalsIgnoreCase(str1, str2) // Case-insensitive string comparison
282
283
// Number utilities
284
std.isEven(x) // Test if number is even
285
std.isOdd(x) // Test if number is odd
286
std.isInteger(x) // Test if number is integer
287
std.isDecimal(x) // Test if number is decimal
288
289
// Logical operations
290
std.xor(x, y) // Exclusive or
291
std.xnor(x, y) // Exclusive nor
292
293
// Comparison utilities
294
std.primitiveEquals(a, b) // Primitive equality comparison
295
```
296
297
### External Interface Functions
298
299
Functions for accessing external data and functionality.
300
301
```jsonnet { .api }
302
std.extVar(x) // Access external variables set via -V or ext_vars
303
std.native(name) // Access native callback functions registered from host language
304
```
305
306
## Usage Examples
307
308
**String manipulation:**
309
```jsonnet
310
{
311
original: " Hello World! ",
312
trimmed: std.trim(self.original),
313
upper: std.asciiUpper(self.trimmed),
314
parts: std.split(self.trimmed, " "),
315
rejoined: std.join("-", self.parts),
316
replaced: std.strReplace(self.original, "World", "Jsonnet")
317
}
318
```
319
320
**Array processing:**
321
```jsonnet
322
local numbers = [1, 2, 3, 4, 5];
323
{
324
doubled: std.map(function(x) x * 2, numbers),
325
evens: std.filter(function(x) x % 2 == 0, numbers),
326
sum: std.sum(numbers),
327
sorted_desc: std.sort(numbers, function(x) -x),
328
unique_items: std.uniq(std.sort([1, 2, 2, 3, 1, 4]))
329
}
330
```
331
332
**Object manipulation:**
333
```jsonnet
334
local config = {
335
name: "app",
336
version: "1.0",
337
debug:: true, // hidden field
338
port: 8080
339
};
340
{
341
fields: std.objectFields(config),
342
all_fields: std.objectFieldsAll(config),
343
has_debug: std.objectHasAll(config, "debug"),
344
config_pairs: std.objectKeysValues(config),
345
without_port: std.objectRemoveKey(config, "port")
346
}
347
```
348
349
**Mathematical operations:**
350
```jsonnet
351
{
352
calculations: {
353
sqrt_of_16: std.sqrt(16),
354
sin_pi_half: std.sin(std.pi / 2),
355
log_base_2: std.log(8) / std.log(2),
356
clamped: std.clamp(15, 0, 10),
357
rounded: std.round(3.7)
358
},
359
angle_conversion: {
360
degrees_to_rad: std.deg2rad(90),
361
radians_to_deg: std.rad2deg(std.pi)
362
}
363
}
364
```
365
366
**Data format conversion:**
367
```jsonnet
368
local data = { users: [{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }] };
369
{
370
json_minified: std.manifestJsonMinified(data),
371
yaml_format: std.manifestYamlDoc(data),
372
python_format: std.manifestPython(data.users),
373
ini_format: std.manifestIni({
374
section1: { key1: "value1", key2: "value2" },
375
section2: { key3: "value3" }
376
})
377
}
378
```
379
380
**Working with external variables:**
381
```jsonnet
382
// Use with: jsonnet -V environment=production -V debug=false config.jsonnet
383
{
384
environment: std.extVar("environment"),
385
debug_mode: std.extVar("debug") == "true",
386
log_level: if std.extVar("environment") == "production" then "warn" else "debug",
387
database_url: if std.extVar("environment") == "production"
388
then "prod-db.example.com"
389
else "dev-db.example.com"
390
}
391
```
392
393
**Set operations:**
394
```jsonnet
395
local set1 = ["a", "b", "c"];
396
local set2 = ["b", "c", "d"];
397
{
398
union: std.setUnion(set1, set2),
399
intersection: std.setInter(set1, set2),
400
difference: std.setDiff(set1, set2),
401
is_member: std.setMember("b", set1)
402
}
403
```
404
405
**Complex example with multiple functions:**
406
```jsonnet
407
local users = [
408
{ name: "Alice Johnson", email: "alice@example.com", age: 30, active: true },
409
{ name: "Bob Smith", email: "bob@example.com", age: 25, active: false },
410
{ name: "Charlie Brown", email: "charlie@example.com", age: 35, active: true }
411
];
412
413
{
414
// Process user data
415
active_users: std.filter(function(user) user.active, users),
416
417
// Transform and format
418
user_summary: std.map(function(user) {
419
name: user.name,
420
initials: std.join("", std.map(
421
function(part) part[0],
422
std.split(user.name, " ")
423
)),
424
contact: std.format("<%s>", user.email),
425
age_group: if user.age < 30 then "young" else "experienced"
426
}, self.active_users),
427
428
// Statistics
429
stats: {
430
total_users: std.length(users),
431
active_count: std.length(self.active_users),
432
average_age: std.round(
433
std.sum(std.map(function(user) user.age, users)) / std.length(users)
434
),
435
all_emails: std.join(", ", std.map(function(user) user.email, users))
436
},
437
438
// Export formatted data
439
yaml_export: std.manifestYamlDoc({
440
users: self.user_summary,
441
generated_at: "2024-01-01T00:00:00Z"
442
})
443
}
444
```