Jsonnet - The Data Templating Language
Description: The Jsonnet language allows elegant and easy description of JSON data.
Keywords: Jsonnet, JSON, YAML, language, configuration, configuration language, functional, declarative, lazy, structured, elegant, semantics, clean, mixins, inheritance, template, expansion, expand

The data templating language
Jsonnet

1. User docs
   Tutorial Demo Standard Library
2. Case Studies
   Fractal
3. Language
   Design Comparisons Specification
4. Implementation
   Cmdline Tool Libraries C++ Internals Javascript Tests
5. Contributing

# Standard Library

This page describes the functions available in Jsonnet's standard library, i.e. the object implicitly bound to the `std` variable. Some of the standard library functions can be implemented in Jsonnet. Their code can be found in the `std.jsonnet` file. The behavior of some of the other functions, i.e. the ones that expose extra functionality not otherwise available to programmers, is described formally in the specification.

The standard library is implicitly added to all Jsonnet programs by enclosing them in a local construct. For example, if the program given by the user is `{x: "foo"}`, then the actual code executed would be `local std = { ... }; {x: "foo"}`. The functions in the standard library are all hidden fields of the `std` object.

### External Variables

#### std.extVar(x)

If an external variable with the given name was defined, return its string value. Otherwise, raise an error.

### Types and Reflection

#### std.type(x)

Return a string that indicates the type of the value. The possible return values are: "array", "boolean", "function", "null", "number", "object", and "string".

#### std.length(x)

Depending on the type of the value given, either returns the number of elements in the array, the number of codepoints in the string, the number of parameters in the function, or the number of fields in the object. Raises an error if given a primitive value, i.e. `null`, `true` or `false`.

#### std.objectHas(o, f)

Returns `true` if the given object has the field (given as a string), otherwise `false`. Raises an error if the arguments are not object and string respectively. Note that hidden fields are not visible via reflection.

#### std.objectFields(o)

Returns an array of strings, each element being a field from the given object. Note that hidden fields are not visible via reflection.

### Mathematical Utilities

The following mathematical functions are available: `std.abs(n)`, `std.max(a, b)`, `std.min(a, b)`, `std.pow(x, n)`, `std.exp(x)`, `std.exponent(x)`, `std.mantissa(x)`, `std.floor(x)`, `std.ceil(x)`, `std.sqrt(x)`, `std.sin(x)`, `std.cos(x)`, `std.tan(x)`, `std.asin(x)`, `std.acos(x)`, and `std.atan(x)`.

The function `std.mod(a, b)` is what the % operator is desugared to. It performs modulo arithmetic if the left hand side is a number, or if the left hand side is a string, it does Python-style string formatting with `std.format()`.

### Assertions and Debugging

#### std.assertEqual(a, b)

Ensure that `a == b`. Returns `true` or throws an error message.

### String Manipulation

#### std.toString(a)

Convert the given argument to a string.

#### std.codepoint(str)

Returns the positive integer representing the unicode codepoint of the character in the given single-character string. This function is the inverse of `std.char(n)`.

#### std.char(n)

Returns a string of length one whose only unicode codepoint has integer id `n`. This function is the inverse of `std.codepoint(str)`.

#### std.substr(s, from, len)

Returns a string that is the part of `s` that starts at offset `from` and is `len` codepoints long.

#### std.split(str, c)

Split the string `str` into an array of strings, divided by the single character `c`.

Example: `std.split("foo/bar", "/")` yields `["foo", "bar"]`.

Example: `std.split("/foo/", "/")` yields `["" "foo", ""]`.

#### std.stringChars(str)

Split the string `str` into an array of strings, each containing a single codepoint.

Example: `std.stringChars("foo")` yields `["f", "o", "o"]`.

#### std.format(str, vals)

Format the string `str` using the values in `vals`. The values can be an array, an object, or in other cases are treated as if they were provided in a singleton array. The string formatting follows the same rules as Python. The `%` operator can be used as a shorthand for this function.

Example: `std.format("Hello %03d", 12)` yields `"Hello 012"`.

Example: `"Hello %03d" % 12` yields `"Hello 012"`.

Example: `"Hello %s, age %d" % ["Foo", 25]` yields `"Hello Foo, age 25"`.

Example: `"Hello %(name)s, age %(age)d" % {age: 25, name: "Foo"}` yields `"Hello Foo, age 25"`.

#### std.escapeStringBash(str)

Wrap `str` in single quotes, and escape any single quotes within `str` by changing them to a sequence `'"'"'`. This allows injection of arbitrary strings as arguments of commands in bash scripts.

#### std.escapeStringDollars(str)

Convert $ to $$ in `str`. This allows injection of arbitrary strings into systems that use $ for string interpolation (like Terraform).

#### std.escapeStringJson(str)

Convert `str` to allow it to be embedded in a JSON representation, within a string. This adds quotes, escapes backslashes, and escapes unprintable characters.

Example:
`{ local description = "Multiline\nc:\\path", json: "{name: %s}" % std.escapeStringJson(description) }`
yields: `{"json": "{name: \"Multiline\\nc:\\\\path\"}"}`

#### std.escapeStringPython(str)

Convert `str` to allow it to be embedded in Python. This is an alias for std.escapeStringJson.

### Manifestation

#### std.manifestIni(v)

Convert the given structure to a string in INI format. This allows using Jsonnet's object model to build a configuration to be consumed by an application expecting an INI file. The data is in the form of a set of sections, each containing a key/value mapping. These examples should make it clear:

`{ main: { a: "1", b: "2" }, sections: { s1: {x: "11", y: "22", z: "33"}, s2: {p: "yes", q: ""}, empty: {}, } }`

Yields a string containing this INI file:

`a = 1 b = 2 [empty] [s1] x = 11 y = 22 z = 33 [s2] p = yes q =`

#### std.manifestPython(v)

Convert the given value to a JSON-like form that is compatible with Python. The chief differences are True / False / None instead of true / false / null.

`{ b: ["foo", "bar"], c: true, d: null, e: { f1: false, f2: 42 }, }`

Yields a string containing this Python code:

`{"b": ["foo", "bar"], "c": True, "d": None, "e": {"f1": False, "f2": 42}}`

#### std.manifestPythonVars(v)

Convert the given object to a JSON-like form that is compatible with Python. The key difference to `std.manifestPython` is that the top level is represented as a list of Python global variables.

`{ b: ["foo", "bar"], c: true, d: null, e: { f1: false, f2: 42 }, }`

Yields a string containing this Python code:

`b = ["foo", "bar"] c = True d = None e = {"f1": False, "f2": 42}`

### Arrays

#### std.makeArray(sz, func)

Create a new array of `sz` elements by calling `func(i)` to initialize each element. Func is expected to be a function that takes a single parameter, the index of the element it should initialize.

Example: `std.makeArray(3,function(x) x * x)` yields `[0, 1, 4]`.

#### std.map(func, arr)

Apply the given function to every element of the array to form a new array.

#### std.filterMap(filter_func, map_func, arr)

This is primarily used to desugar array comprehension syntax. It first filters, then maps thte given array, using the two functions provided.

#### std.filter(func, arr)

Return a new array containing all the elements of `arr` for which the `func` function returns true.

#### std.foldl(func, arr, init)

Classic foldl function. Calls the function on each array element and the result of the previous function call, or `init` in the case of the initial element. Traverses the array from left to right.

#### std.foldr(func, arr, init)

Classic foldl function. Calls the function on each array element and the result of the previous function call, or `init` in the case of the initial element. Traverses the array from right to left.

#### std.range(from, to)

Return an array of ascending numbers between the two limits, inclusively.

#### std.join(sep, arr)

If `sep` is a string, then `arr` must be an array of strings, in which case they are concatenated with `sep` used as a delimiter. If `sep` is an array, then `arr` must be an array of arrays, in which case the arrays are concatenated in the same way, to produce a single array.

Example1: `std.join(".", ["www", "google", "com"])` yields `"www.google.com"`.

Example2: `std.join([9, 9], [[1], [2, 3]])` yields `[1, 9, 9, 2, 3]`.

#### std.lines(arr)

Concatenate an array of strings into a text file with newline characters after each string. This is suitable for constructing bash scripts and the like.

#### std.flattenArrays(arrs)

Concatenate an array of arrays into a single array.

### Base 64

#### std.base64(v)

Encodes the given value into a base64 string. The encoding sequence is A-Za-z0-9+/ with = to pad the output to a multiple of 4 characters. The value can be a string or an array of numbers, but the codepoints / numbers must be in the 0 to 255 range. The resulting string has no line breaks.

#### std.base64DecodeBytes(s)

Decodes the given base64 string into an array of bytes (number values). Currently assumes the input string has no linebreaks and is padded to a multiple of 4 (with the = character). In other words, it consumes the output of std.base64().

#### std.base64Decode(s)

Behaves like std.base64DecodeBytes() except returns a string instead of an array of bytes.

### Miscellaneous

#### std.force(x)

Always returns true, but always evaluates its argument. this allows controlling memory usage in recursive algorithms, and causes runtime errors in x to be discovered immediately.

Except as noted, this content is licensed under Creative Commons Attribution 2.5.