### std.slice examples
Source: https://jsonnet.org/ref/stdlib.html
Selects subarrays and substrings using start, end, and step parameters. Includes negative index example.
```jsonnet
std.slice([1, 2, 3, 4, 5, 6], 0, 4, 1)
```
```jsonnet
std.slice([1, 2, 3, 4, 5, 6], 1, 6, 2)
```
```jsonnet
std.slice("jsonnet", 0, 4, 1)
```
```jsonnet
std.slice("jsonnet", -3, null, null)
```
--------------------------------
### Jsonnet output.json from top-level arguments example
Source: https://jsonnet.org/learning/tutorial.html
The resulting output.json from the top-level arguments example, showing the generated cocktail menu with 'Happy Hour' prefix and brunch=true, including the Bloody Mary and Mimosa with 'Cheap Sparkling Wine'.
```json
{ "Happy Hour Bloody Mary": { "garnish": "Celery salt & pepper", "ingredients": [ { "kind": "Vodka", "qty": 1.5 }, { "kind": "Tomato Juice", "qty": 3 }, { "kind": "Lemon Juice", "qty": 1.5 }, { "kind": "Worcestershire", "qty": 0.25 }, { "kind": "Tobasco Sauce", "qty": 0.15 } ], "served": "Tall" }, "Happy Hour Mimosa": { "garnish": "Orange Slice", "ingredients": [ { "kind": "Cheap Sparkling Wine", "qty": 3 }, { "kind": "Orange Juice", "qty": 3 } ], "served": "Champagne Flute" }, "Happy Hour Pina Colada": { "garnish": "Pineapple slice", "ingredients": [ { "kind": "Rum", "qty": 3 }, { "kind": "Pineapple Juice", "qty": 6 }, { "kind": "Coconut Cream", "qty": 2 }, { "kind": "Ice", "qty": 12 } ], "served": "Frozen" } }
```
--------------------------------
### Object-orientation example
Source: https://jsonnet.org/
Shows how to eliminate duplication using object-orientation. The example defines two persons, where person2 inherits from person1 and overrides the name. The output is shown as JSON.
```jsonnet
// Edit me! {
person1: {
name: "Alice",
welcome: "Hello " + self.name + "!",
},
person2: self.person1 { name: "Bob" },
}
```
```json
{
"person1": {
"name": "Alice",
"welcome": "Hello Alice!"
},
"person2": {
"name": "Bob",
"welcome": "Hello Bob!"
}
}
```
--------------------------------
### Jsonnet object inheritance example: templates.libsonnet with Sour template
Source: https://jsonnet.org/learning/tutorial.html
This example shows how to import a template library and create specialized cocktails by overriding fields of the Sour template. It demonstrates field overriding, using +: to modify fields, and adding to lists.
```jsonnet
local templates = import 'templates.libsonnet';
{
// The template requires us to override
// the 'spirit'.
'Whiskey Sour': templates.Sour {
spirit: 'Whiskey',
},
// Specialize it further.
'Deluxe Sour': self['Whiskey Sour'] {
// Don't replace the whole sweetner,
// just change 'kind' within it.
sweetener+: { kind: 'Gomme Syrup' },
},
Daiquiri: templates.Sour {
spirit: 'Banks 7 Rum',
citrus+: { kind: 'Lime' },
// Any field can be overridden.
garnish: 'Lime wedge',
},
"Nor'Easter": templates.Sour {
spirit: 'Whiskey',
citrus: { kind: 'Lime', qty: 0.5 },
sweetener+: { kind: 'Maple Syrup' },
// +: Can also add to a list.
ingredients+: [
{ kind: 'Ginger Beer', qty: 1 },
],
},
}
```
--------------------------------
### Jsonnet arithmetic and operations example
Source: https://jsonnet.org/learning/tutorial.html
Demonstrates arithmetic, bitwise, boolean, object merging, membership, and string formatting in Jsonnet. The example includes comments explaining each operation. The output is shown in the following block.
```jsonnet
{ concat\_array: \[1, 2, 3\] + \[4\], concat\_string: '123' + 4, equality1: 1 == '1', equality2: \[{}, { x: 3 - 1 }\] == \[{}, { x: 2 }\], ex1: 1 + 2 \* 3 / (4 + 5), // Bitwise operations first cast to int. ex2: self.ex1 | 3, // Modulo operator. ex3: self.ex1 % 2, // Boolean logic ex4: (4 > 3) && (1 <= 3) || false, // Mixing objects together obj: { a: 1, b: 2 } + { b: 3, c: 4 }, // Test if a field is in an object obj\_member: 'foo' in { foo: 1 }, // String formatting str1: 'The value of self.ex2 is ' + self.ex2 + '.', str2: 'The value of self.ex2 is %g.' % self.ex2, str3: 'ex1=%0.2f, ex2=%0.2f' % \[self.ex1, self.ex2\], // By passing self, we allow ex1 and ex2 to // be extracted internally. str4: 'ex1=%(ex1)0.2f, ex2=%(ex2)0.2f' % self, // Do textual templating of entire files: str5: ||| ex1=%(ex1)0.2f ex2=%(ex2)0.2f ||| % self, }
```
```json
{ "concat\_array": \[ 1, 2, 3, 4 \], "concat\_string": "1234", "equality1": false, "equality2": true, "ex1": 1.6666666666666665, "ex2": 3, "ex3": 1.6666666666666665, "ex4": true, "obj": { "a": 1, "b": 3, "c": 4 }, "obj\_member": true, "str1": "The value of self.ex2 is 3.", "str2": "The value of self.ex2 is 3.", "str3": "ex1=1.67, ex2=3.00", "str4": "ex1=1.67, ex2=3.00", "str5": "ex1=1.67\\nex2=3.00\\n" }
```
--------------------------------
### Jsonnet example with assertions and error handling
Source: https://jsonnet.org/learning/tutorial.html
An interactive Jsonnet example that extends a previous example to sanity check input. It defines functions with assertions and error checks, and includes an object with field assertions. The output is shown in the following block.
```jsonnet
// Extend above example to sanity check input.
local equal_parts(size, ingredients) =
local qty = size / std.length(ingredients);
// Check a pre-condition
if std.length(ingredients) == 0 then
error 'Empty ingredients.'
else
[ { kind: i, qty: qty } for i in ingredients ];
local subtract(a, b) =
assert a > b : 'a must be bigger than b';
a - b;
assert std.isFunction(subtract);
{
test1: equal_parts(1, ['Whiskey']),
test2: subtract(10, 3),
object: {
assert self.f < self.g : 'wat',
f: 1,
g: 2,
},
assert std.isObject(self.object),
}
```
```json
{
"object": {
"f": 1,
"g": 2
},
"test1": [
{
"kind": "Whiskey",
"qty": 1
}
],
"test2": 7
}
```
--------------------------------
### Run jsonnet -S ini.jsonnet
Source: https://jsonnet.org/articles/output-formats.html
Command to execute the INI example. The -S flag prints the string verbatim rather than as JSON.
```bash
$ jsonnet -S ini.jsonnet
```
--------------------------------
### std.trace example with conditional return
Source: https://jsonnet.org/ref/stdlib.html
Shows how to use std.trace to output a message to stderr and return a value. The example defines a local function conditionalReturn that uses std.trace to log which branch is taken. The output shows the trace message and the resulting JSON object.
```jsonnet
local conditionalReturn(cond, in1, in2) =
if (cond) then
std.trace('cond is true returning '
+ std.toString(in1), in1)
else
std.trace('cond is false returning '
+ std.toString(in2), in2);
{
a: conditionalReturn(true, { b: true }, { c: false }),
}
```
```output
TRACE: test.jsonnet:3 cond is true returning {"b": true}
{
"a": {
"b": true
}
}
```
--------------------------------
### std.repeat examples
Source: https://jsonnet.org/ref/stdlib.html
Repeats an array and a string a given number of times.
```jsonnet
std.repeat([1, 2, 3], 3)
```
```jsonnet
std.repeat("blah", 2)
```
--------------------------------
### Python API example: evaluate_snippet with ext_vars
Source: https://jsonnet.org/ref/bindings.html
Example of using the Python API to evaluate a Jsonnet snippet. It imports the _jsonnet module, defines a Jsonnet string with external variables, calls evaluate_snippet with ext_vars, parses the JSON output, and prints the results. Requires the jsonnet package installed.
```python
import json
import _jsonnet
jsonnet_str = '''
{
person1: {
name: "Alice",
welcome: "Hello " + self.name + "!",
},
person2: self.person1 {
name: std.extVar("OTHER_NAME"),
},
}
'''
json_str = _jsonnet.evaluate_snippet(
"snippet", jsonnet_str,
ext_vars={'OTHER_NAME': 'Bob'})
json_obj = json.loads(json_str)
for person_id, person in json_obj.items():
print('%s is %s, greeted by "%s"' % (
person_id,
person['name'],
person['welcome']))
```
--------------------------------
### Evaluate a Jsonnet file with output
Source: https://jsonnet.org/learning/getting_started.html
Run jsonnet on a file to evaluate it and print the resulting JSON to stdout. The example shows the output for landingpage.jsonnet.
```bash
$ jsonnet landingpage.jsonnet
{
"person1": {
"name": "Alice",
"welcome": "Hello Alice!"
},
"person2": {
"name": "Bob",
"welcome": "Hello Bob!"
}
}
```
--------------------------------
### Jsonnet abstract template example: Sour template definition
Source: https://jsonnet.org/learning/tutorial.html
This example defines an abstract template for a 'sour' cocktail. It uses hidden fields (::) for citrus, sweetener, and spirit, and requires the spirit to be overridden. The ingredients list is built from these fields.
```jsonnet
{
// Abstract template of a "sour" cocktail.
Sour: {
local drink = self,
// Hidden fields can be referred to
// and overridden, but do not appear
// in the JSON output.
citrus:: { kind: 'Lemon Juice', qty: 1 },
sweetener:: { kind: 'Simple Syrup', qty: 0.5 },
// A field that must be overridden.
spirit:: error 'Must override "spirit"',
ingredients: [
{ kind: drink.spirit, qty: 2 },
drink.citrus,
drink.sweetener,
],
garnish: self.citrus.kind + ' twist',
served: 'Straight Up',
},
}
```
--------------------------------
### Functions example
Source: https://jsonnet.org/
Shows how to use functions to generate objects. The Person function has a default parameter 'Alice' and returns an object with a welcome message. The output is shown as JSON.
```jsonnet
// A function that returns an object.
local Person(name='Alice') = {
name: name,
welcome: 'Hello ' + name + '!',
};
{
person1: Person(),
person2: Person('Bob'),
}
```
```json
{
"person1": {
"name": "Alice",
"welcome": "Hello Alice!"
},
"person2": {
"name": "Bob",
"welcome": "Hello Bob!"
}
}
```
--------------------------------
### Jsonnet output example: output.json for cocktail mixins
Source: https://jsonnet.org/learning/tutorial.html
This is the JSON output produced by the mixin example. It shows the resulting objects for 'Virgin Daiquiri', 'Virgin Whiskey Sour', and 'Whiskey Sour' after applying the mixins.
```json
{
"Virgin Daiquiri": {
"garnish": "Lime wedge",
"ingredients": [
{ "kind": "Water", "qty": 2 },
{ "kind": "Vanilla Essence", "qty": "dash" },
{ "kind": "Angustura Bitters", "qty": "dash" },
{ "kind": "Lime", "qty": 1 },
{ "kind": "Simple Syrup", "qty": 0.5 }
],
"served": "Straight Up"
},
"Virgin Whiskey Sour": {
"garnish": "Lemon Juice twist",
"ingredients": [
{ "kind": "Water", "qty": 2 },
{ "kind": "Angustura Bitters", "qty": "tsp" },
{ "kind": "Lemon Juice", "qty": 1 },
{ "kind": "Simple Syrup", "qty": 0.5 }
],
"served": "Straight Up"
},
"Whiskey Sour": {
"ingredients": [
{ "kind": "Whiskey", "qty": 2 },
{ "kind": "Lemon Juice", "qty": 1 },
{ "kind": "Simple Syrup", "qty": 0.5 }
],
"served": "In a plastic cup"
}
}
```
--------------------------------
### Output JSON for external variables example
Source: https://jsonnet.org/learning/tutorial.html
The resulting JSON output when the external variables example is evaluated with the given command line. It shows the generated cocktail objects, including the conditional 'Bloody Mary' and the Mimosa using 'Cheap Sparkling Wine'.
```json
{
"Happy Hour Bloody Mary": {
"garnish": "Celery salt & pepper",
"ingredients": [
{ "kind": "Vodka", "qty": 1.5 },
{ "kind": "Tomato Juice", "qty": 3 },
{ "kind": "Lemon Juice", "qty": 1.5 },
{ "kind": "Worcestershire", "qty": 0.25 },
{ "kind": "Tobasco Sauce", "qty": 0.15 }
],
"served": "Tall"
},
"Happy Hour Mimosa": {
"garnish": "Orange Slice",
"ingredients": [
{ "kind": "Cheap Sparkling Wine", "qty": 3 },
{ "kind": "Orange Juice", "qty": 3 }
],
"served": "Champagne Flute"
},
"Happy Hour Pina Colada": {
"garnish": "Pineapple slice",
"ingredients": [
{ "kind": "Rum", "qty": 3 },
{ "kind": "Pineapple Juice", "qty": 6 },
{ "kind": "Coconut Cream", "qty": 2 },
{ "kind": "Ice", "qty": 12 }
],
"served": "Frozen"
}
}
```
--------------------------------
### std.makeArray example
Source: https://jsonnet.org/ref/stdlib.html
Creates an array of 3 elements by squaring each index, yielding [ 0, 1, 4 ].
```jsonnet
std.makeArray(3,function(x) x * x)
```
--------------------------------
### std.flatMap examples
Source: https://jsonnet.org/ref/stdlib.html
Shows four uses of std.flatMap: duplicating elements, filtering with empty arrays, mapping with multiplication, and concatenating strings.
```jsonnet
std.flatMap(function(x) [x, x], [1, 2, 3])
```
```jsonnet
std.flatMap(function(x) if x == 2 then [] else [x], [1, 2, 3])
```
```jsonnet
std.flatMap(function(x) if x == 2 then [] else [x * 3, x * 2], [1, 2, 3])
```
```jsonnet
std.flatMap(function(x) x+x, "foo")
```
--------------------------------
### Object literal example
Source: https://jsonnet.org/ref/language.html
Shows a basic Jsonnet object with nested objects and arithmetic expressions.
```jsonnet
{
"foo": 1,
"bar": {
"arr": [1, 2, 3],
"number": 10 + 7,
}
}
```
--------------------------------
### YAML Kubernetes example input for conversion
Source: https://jsonnet.org/articles/kubernetes.html
Input YAML for the conversion tool. It is a ReplicationController for spark-master with a single container. The tool converts YAML to JSON and then formats it as Jsonnet.
```yaml
kind: ReplicationController
apiVersion: v1
metadata:
name: spark-master-controller
spec:
replicas: 1
selector:
component: spark-master
template:
metadata:
labels:
component: spark-master
spec:
containers:
- name: spark-master
image: k8s.gcr.io/spark:1.5.2_v1
command: ["/start-master"]
ports:
- containerPort: 7077
- containerPort: 8080
resources:
requests:
cpu: 100m
```
--------------------------------
### Jsonnet syntax example with cocktails
Source: https://jsonnet.org/learning/tutorial.html
Interactive example showing Jsonnet syntax: unquoted field names, trailing commas, comments, single/double quoted strings, text blocks (|||), verbatim strings (@'...'), and numeric underscores. The output shows the evaluated JSON with escaped characters and newlines.
```jsonnet
/* A C-style comment. */ # A Python-style comment. {
cocktails: {
// Ingredient quantities are in fl oz.
'Tom Collins': {
ingredients: [
{ kind: "Farmer's Gin", qty: 1.5 },
{ kind: 'Lemon', qty: 1 },
{ kind: 'Simple Syrup', qty: 0.5 },
{ kind: 'Soda', qty: 2 },
{ kind: 'Angostura', qty: 'dash' },
],
garnish: 'Maraschino Cherry',
served: 'Tall',
description: |||
The Tom Collins is essentially gin and lemonade.
The bitters add complexity.
|||,
},
Manhattan: {
ingredients: [
{ kind: 'Rye', qty: 2.5 },
{ kind: 'Sweet Red Vermouth', qty: 1 },
{ kind: 'Angostura', qty: 'dash' },
],
garnish: 'Maraschino Cherry',
served: 'Straight Up',
description: @'A clear \ red drink.',
},
},
}
```
```json
{
"cocktails": {
"Manhattan": {
"description": "A clear \\ red drink.",
"garnish": "Maraschino Cherry",
"ingredients": [
{ "kind": "Rye", "qty": 2.5 },
{ "kind": "Sweet Red Vermouth", "qty": 1 },
{ "kind": "Angostura", "qty": "dash" }
],
"served": "Straight Up"
},
"Tom Collins": {
"description": "The Tom Collins is essentially gin and\nlemonade. The bitters add complexity.\n",
"garnish": "Maraschino Cherry",
"ingredients": [
{ "kind": "Farmer's Gin", "qty": 1.5 },
{ "kind": "Lemon", "qty": 1 },
{ "kind": "Simple Syrup", "qty": 0.5 },
{ "kind": "Soda", "qty": 2 },
{ "kind": "Angostura", "qty": "dash" }
],
"served": "Tall"
}
}
}
```
--------------------------------
### output.svg
Source: https://jsonnet.org/articles/output-formats.html
The SVG output generated by the custom manifestation example. Shows the resulting XML structure.
```xml
```
--------------------------------
### std.manifestTomlEx example with TOML output
Source: https://jsonnet.org/ref/stdlib.html
Converts a Jsonnet object to TOML using two-space indentation. The output shows the resulting TOML file, including arrays and nested sections.
```jsonnet
std.manifestTomlEx({
key1: "value",
key2: 1,
section: {
a: 1,
b: "str",
c: false,
d: [1, "s", [2, 3]],
subsection: {
k: "v",
},
},
sectionArray: [
{ k: "v1", v: 123 },
{ k: "v2", c: "value2" },
],
}, " ")
```
```toml
key1 = "value"
key2 = 1
[section]
a = 1
b = "str"
c = false
d = [
1,
"s",
[ 2, 3 ]
]
[section.subsection]
k = "v"
[[sectionArray]]
k = "v1"
v = 123
[[sectionArray]]
c = "value2"
k = "v2"
```
--------------------------------
### std.manifestPython example
Source: https://jsonnet.org/ref/stdlib.html
Converts a Jsonnet value to a Python-compatible representation, using True/False/None instead of true/false/null. The input object is shown with its corresponding Python output.
```jsonnet
{
b: ["foo", "bar"],
c: true,
d: null,
e: { f1: false, f2: 42 },
}
```
```python
{
"b": ["foo", "bar"],
"c": True,
"d": None,
"e": {"f1": False, "f2": 42}
}
```
--------------------------------
### Jsonnet error and assert syntax examples
Source: https://jsonnet.org/learning/tutorial.html
Shows the basic syntax for raising errors and asserting conditions in Jsonnet, including custom failure messages and assertions on object fields.
```jsonnet
error "foo"
```
```jsonnet
assert "foo";
```
```jsonnet
assert "foo" : "message";
```
```jsonnet
assert self.f == 10,
```
```jsonnet
assert self.f == 10 : "message",
```
--------------------------------
### std.manifestPythonVars example
Source: https://jsonnet.org/ref/stdlib.html
Converts a Jsonnet object to a list of Python global variable assignments. The input object is the same as for manifestPython, but the output is a series of variable assignments.
```jsonnet
{
b: ["foo", "bar"],
c: true,
d: null,
e: { f1: false, f2: 42 },
}
```
```python
b = ["foo", "bar"]
c = True
d = None
e = {"f1": False, "f2": 42}
```
--------------------------------
### Field name expressions example
Source: https://jsonnet.org/ref/language.html
Shows dynamic field names computed at object creation. Field names cannot refer to object locals, self, or super.
```jsonnet
{
a: 1,
"a a": 2,
"ąę": 3,
["aaa" + "bbb"]: 4,
}
```
--------------------------------
### Jsonnet referential transparency example
Source: https://jsonnet.org/ref/language.html
Shows a recursive function pow2 and its call. The call can be replaced with its definition without changing the program's meaning.
```jsonnet
local pow2(n) = if n == 0 then 1 else 2 * pow2(n - 1);
pow2(17)
```
--------------------------------
### Writing a library of functions with local variables
Source: https://jsonnet.org/learning/tutorial.html
Shows how to write a Jsonnet library (utils.libsonnet) with a function equal_parts that uses a function-scoped local variable. The example imports the library and uses the function to create a Negroni cocktail.
```jsonnet
local utils = import 'utils.libsonnet'; { Negroni: { // Divide 3oz among the 3 ingredients. ingredients: utils.equal_parts(3, [ 'Farmers Gin', 'Sweet Red Vermouth', 'Campari', ]), garnish: 'Orange Peel', served: 'On The Rocks', }, }
```
```jsonnet
{ equal_parts(size, ingredients):: // Define a function-scoped variable. local qty = size / std.length(ingredients); // Return an array. [ { kind: i, qty: qty } for i in ingredients ], }
```
```json
{ "Negroni": { "garnish": "Orange Peel", "ingredients": [ { "kind": "Farmers Gin", "qty": 1 }, { "kind": "Sweet Red Vermouth", "qty": 1 }, { "kind": "Campari", "qty": 1 } ], "served": "On The Rocks" } }
```
--------------------------------
### Object equality with functions example
Source: https://jsonnet.org/ref/language.html
Shows that objects with visible fields that cannot be checked for equality (like functions) are not allowed to be compared. Such fields should be hidden.
```jsonnet
{
a: function() 42
} == {
a: function() 42
}
```
--------------------------------
### Jsonnet function parameters example
Source: https://jsonnet.org/ref/language.html
Shows a function with a required parameter x and an optional parameter y with default 1, and various valid call styles: positional, named, and mixed.
```jsonnet
local foo(x, y=1) = x + y;
[
foo(1),
foo(1, 1),
foo(x=1, y=1),
foo(y=1, x=1),
foo(x=1),
]
```
--------------------------------
### std.manifestIni example
Source: https://jsonnet.org/articles/output-formats.html
Jsonnet code that uses std.manifestIni to serialize a structure with a main section and nested sections into INI format. The main section holds top-level keys.
```jsonnet
std.manifestIni({ main: { a: 1, }, sections: { foo: { a: true, b: 2, }, bar: { x: 'text', }, }, })
```
--------------------------------
### std.parseYaml example
Source: https://jsonnet.org/ref/stdlib.html
Parses a YAML string into a Jsonnet value. The parser is best-effort and only supports YAML that is compatible with JSON; the root must be a sequence or map. std.parseYaml('foo: bar') yields { "foo": "bar" }.
```jsonnet
std.parseYaml('foo: bar')
```
--------------------------------
### Integrate with existing applications
Source: https://jsonnet.org/
Shows how to generate multiple configuration files (uwsgi.ini, init.sh, cassandra.conf) from a single Jsonnet script using std.manifestIni, text blocks, and std.manifestYamlDoc. The output is shown as the contents of the generated files.
```jsonnet
local application = 'my-app';
local module = 'uwsgi_module';
local dir = '/var/www';
local permission = 644;
{
'uwsgi.ini': std.manifestIni({
sections: {
uwsgi: {
module: module,
pythonpath: dir,
socket: dir + '/uwsgi.sock',
'chmod-socket': permission,
callable: application,
logto: '/var/log/uwsgi/uwsgi.log',
},
},
}),
'init.sh': |||
#!/usr/bin/env bash
mkdir -p %(dir)s
touch %(dir)s/initialized
chmod %(perm)d %(dir)s/initialized
||| % {dir: dir, perm: permission},
'cassandra.conf': std.manifestYamlDoc({
cluster_name: application,
seed_provider: [
{
class_name: 'SimpleSeedProvider',
parameters: [{ seeds: '127.0.0.1' }],
},
],
}),
}
```
```text
"cluster_name": "my-app"
"seed_provider":
- "class_name": "SimpleSeedProvider"
"parameters":
- "seeds": "127.0.0.1"
#!/usr/bin/env bash
mkdir -p /var/www
touch /var/www/initialized
chmod 644 /var/www/initialized
[uwsgi]
callable = my-app
chmod-socket = 644
logto = /var/log/uwsgi/uwsgi.log
module = uwsgi_module
pythonpath = /var/www
socket = /var/www/uwsgi.sock
```
--------------------------------
### FractalInstance resource with configuration and startup script
Source: https://jsonnet.org/articles/fractal.2.html
Defines a FractalInstance resource with a conf object extending ApplicationConf and a startup_script that appends a line to add a file. The conf includes database settings and tilegen address.
```jsonnet
resource.FractalInstance(k) {
...
conf:: ApplicationConf {
database_name: cassandraKeyspace,
database_user: cassandraUser,
database_pass: credentials.cassandraUserPass,
tilegen: "${google_compute_address.tilegen.address}",
db_endpoints: cassandraNodes,
},
startup_script +: [self.addFile(self.conf, "/var/www/conf.json")],
}
```
--------------------------------
### Conditional fields example
Source: https://jsonnet.org/ref/language.html
If a field name evaluates to null, the field is discarded. This example evaluates to an empty object because the condition is false.
```jsonnet
{
[if 1 == 2 then "foo"]: "bar",
}
```
--------------------------------
### std.substr(str, from, len)
Source: https://jsonnet.org/ref/stdlib.html
Returns a substring of str starting at offset from and len codepoints long. If the string is shorter than from+len, the suffix starting at from is returned.
```APIDOC
## std.substr(str, from, len)
### Description
Returns a string that is the part of `str` that starts at offset `from` and is `len` codepoints long. If the string `str` is shorter than `from+len`, the suffix starting at position `from` will be returned.
### Parameters
- **str** (string) - Required - The input string.
- **from** (integer) - Required - The starting offset (0-based).
- **len** (integer) - Required - The number of codepoints to include.
### Availability
Since version 0.10.0.
### Notes
The slice operator (e.g., `str[from:to]`) can also be used on strings, as an alternative to this function. However, note that the slice operator takes a start and an end index, but `std.substr` takes a start index and a length.
```
--------------------------------
### std.escapeStringJson example
Source: https://jsonnet.org/ref/stdlib.html
Shows how to embed a string with newlines and backslashes into a JSON string representation. The example uses the format operator %s with std.escapeStringJson to produce a quoted and escaped JSON string.
```jsonnet
local description = "Multiline\nc:\\path"; "{name: %s}" % std.escapeStringJson(description)
```
--------------------------------
### Jsonnet: Importing and calling add.jsonnet as a function
Source: https://jsonnet.org/ref/language.html
Shows how to import a Jsonnet program that is a function and call it with arguments, demonstrating that TLA programs can be reused as normal functions.
```jsonnet
local add = import 'add.jsonnet';
add(1, 2)
```
--------------------------------
### Importing a Jsonnet library and using importstr
Source: https://jsonnet.org/learning/tutorial.html
Shows how to import a Jsonnet library (martinis.libsonnet) and a text file (garnish.txt) using importstr. The example defines a local variable for the library and constructs an object with a Manhattan cocktail that uses the imported garnish.
```jsonnet
local martinis = import 'martinis.libsonnet'; { 'Vodka Martini': martinis\['Vodka Martini'\], Manhattan: { ingredients: [ { kind: 'Rye', qty: 2.5 }, { kind: 'Sweet Red Vermouth', qty: 1 }, { kind: 'Angostura', qty: 'dash' }, ], garnish: importstr 'garnish.txt', served: 'Straight Up', }, }
```
```jsonnet
{ 'Vodka Martini': { ingredients: [ { kind: 'Vodka', qty: 2 }, { kind: 'Dry White Vermouth', qty: 1 }, ], garnish: 'Olive', served: 'Straight Up', }, Cosmopolitan: { ingredients: [ { kind: 'Vodka', qty: 2 }, { kind: 'Triple Sec', qty: 0.5 }, { kind: 'Cranberry Juice', qty: 0.75 }, { kind: 'Lime Juice', qty: 0.5 }, ], garnish: 'Orange Peel', served: 'Straight Up', }, }
```
```json
{ "Manhattan": { "garnish": "Maraschino Cherry", "ingredients": [ { "kind": "Rye", "qty": 2.5 }, { "kind": "Sweet Red Vermouth", "qty": 1 }, { "kind": "Angostura", "qty": "dash" } ], "served": "Straight Up" }, "Vodka Martini": { "garnish": "Olive", "ingredients": [ { "kind": "Vodka", "qty": 2 }, { "kind": "Dry White Vermouth", "qty": 1 } ], "served": "Straight Up" } }
```
--------------------------------
### Jsonnet formatter demo: before and after
Source: https://jsonnet.org/learning/tools.html
Shows the input and output of the formatter demo. The input has unformatted code with comments, imports, a function, and a template object. The output is the formatted version with sorted imports, canonical string quotes, spacing, and trailing commas.
```jsonnet
# Edit me! local b = import "b.libsonnet"; # comment local a = import "a.libsonnet"; local f(x,y)=x+y; local Template = {z: "foo"}; Template + { "f": ((3)) , "g g": f(4,2), arr: [[ 1, 2, ], 3, ] }
```
```jsonnet
// Edit me! local a = import 'a.libsonnet'; local b = import 'b.libsonnet'; // comment local f(x, y) = x + y; local Template = { z: 'foo' }; Template { f: (3), 'g g': f(4, 2), arr: [ [ 1, 2, ], 3, ], }
```
--------------------------------
### Better solution using objects and utils.libsonnet
Source: https://jsonnet.org/articles/kubernetes.html
A better solution using an object to represent the mapping, converting to Kubernetes representation post-hoc. Includes the utils.libsonnet file with pairList and namedObjectList functions.
```jsonnet
local utils = import 'utils.libsonnet';
local PodSpec = {
containersObj:: {
foo: {
envObj:: {
var1: 'somevalue',
var2: 'somevalue',
},
env: utils.pairList(self.envObj),
},
bar: {
envObj:: {
var2: 'somevalue',
var3: 'somevalue',
},
env: utils.pairList(self.envObj),
},
},
containers: utils.namedObjectList(self.containersObj),
};
PodSpec {
containersObj+: {
bar+: {
envObj+: {
var3: 'othervalue'
}
}
}
}
```
```jsonnet
// utils.libsonnet
{
pairList(tab, kfield='name', vfield='value'):: [
{ [kfield]: k, [vfield]: tab[k] } for k in std.objectFields(tab)
],
namedObjectList(tab, name_field='name'):: [
tab[name] + { [name_field]: name } for name in std.objectFields(tab)
],
}
```
--------------------------------
### Jsonnet mixins example: RemoveGarnish and NoAlcohol applied to sours
Source: https://jsonnet.org/learning/tutorial.html
This example demonstrates defining mixins in Jsonnet. RemoveGarnish hides the garnish field, and NoAlcohol substitutes ingredients for non-alcoholic versions. The final object applies these mixins to 'Whiskey Sour', 'Virgin Whiskey Sour', and 'Virgin Daiquiri'.
```jsonnet
local sours = import 'sours-oo.jsonnet';
local RemoveGarnish = {
// Not technically removed, but made hidden.
garnish:: super.garnish,
};
// Make virgin cocktails
local NoAlcohol = {
local Substitute(ingredient) =
local k = ingredient.kind;
local bitters = 'Angustura Bitters';
if k == 'Whiskey' then
[
{ kind: 'Water', qty: ingredient.qty },
{ kind: bitters, qty: 'tsp' },
]
else if k == 'Banks 7 Rum' then
[
{ kind: 'Water', qty: ingredient.qty },
{ kind: 'Vanilla Essence', qty: 'dash' },
{ kind: bitters, qty: 'dash' },
]
else
[ ingredient ],
ingredients: std.flattenArrays([ Substitute(i) for i in super.ingredients ]),
};
local PartyMode = {
served: 'In a plastic cup',
};
{
'Whiskey Sour': sours['Whiskey Sour'] + RemoveGarnish + PartyMode,
'Virgin Whiskey Sour': sours['Whiskey Sour'] + NoAlcohol,
'Virgin Daiquiri': sours.Daiquiri + NoAlcohol,
}
```
--------------------------------
### Jsonnet: Add new instance with new image to google_compute_instance
Source: https://jsonnet.org/articles/fractal.3.html
Shows the configuration after adding a new instance (k=4) with the new image 'appserv-v20150102-1200' while keeping the old instances (k=1,2,3) with the old image. The duplication is temporary to allow easy rollback.
```jsonnet
google_compute_instance: {
["appserv" + k]: resource.FractalInstance(k) {
name: "appserv" + k,
image: "appserv-v20141222-0300",
...
}
for k in [1, 2, 3]
} + {
["appserv" + k]: resource.FractalInstance(k) {
name: "appserv" + k,
image: "appserv-v20150102-1200",
...
}
for k in [4]
} + ...
```
--------------------------------
### Base and Derived object example with self, super, and hidden fields
Source: https://jsonnet.org/learning/tutorial.html
Shows how to derive an object from a base using the + operator, access base fields with super, and use hidden fields (::) that do not appear in output. The output shows the resulting JSON with overridden and inherited fields.
```jsonnet
local Base = { f: 2, g: self.f + 100, };
local WrapperBase = { Base: Base, };
{
Derived: Base + {
f: 5,
old_f: super.f,
old_g: super.g,
},
WrapperDerived: WrapperBase + {
Base+: { f: 5 },
},
}
```
```json
{
"Derived": {
"f": 5,
"g": 105,
"old_f": 2,
"old_g": 105
},
"WrapperDerived": {
"Base": {
"f": 5,
"g": 105
}
}
}
```
--------------------------------
### output.ini
Source: https://jsonnet.org/articles/output-formats.html
The INI output produced by the std.manifestIni example. Note the escaping of section names with backslashes.
```ini
a = 1 \[bar\] x = text \[foo\] a = 1 b = 2
```
--------------------------------
### std.startsWith(a, b)
Source: https://jsonnet.org/ref/stdlib.html
Returns whether the string a is prefixed by the string b.
```APIDOC
## std.startsWith(a, b)
### Description
Returns whether the string `a` is prefixed by the string `b`.
### Parameters
- **a** (string) - Required - The string to check.
- **b** (string) - Required - The prefix to look for.
### Returns
Boolean - `true` if `a` starts with `b`, `false` otherwise.
### Availability
Since version 0.10.0.
```
--------------------------------
### std.manifestJsonMinified output
Source: https://jsonnet.org/ref/stdlib.html
Converts an object to minified JSON. The example shows the input and the resulting single-line JSON output.
```jsonnet
std.manifestJsonMinified(
{
x: [1, 2, 3, true, false, null,
"string\nstring"],
y: { a: 1, b: 2, c: [1, 2] },
})
```
```json
{"x":[1,2,3,true,false,null,"string\nstring"],"y":{"a":1,"b":2,"c":[1,2]}}
```
--------------------------------
### Set external variables with jsonnet --ext-str and --ext-code
Source: https://jsonnet.org/learning/tutorial.html
Command line to bind the external variables 'prefix' and 'brunch' when initializing the Jsonnet virtual machine. 'prefix' is bound to the string 'Happy Hour ' and 'brunch' to true. The --ext-str flag passes a raw string, while --ext-code passes Jsonnet code.
```bash
jsonnet --ext-str prefix="Happy Hour " \
--ext-code brunch=true ...
```
--------------------------------
### std.manifestYamlDoc with indent_array_in_object=false
Source: https://jsonnet.org/ref/stdlib.html
Converts a value to YAML. The example uses indent_array_in_object=false and shows the resulting YAML output with quoted keys.
```jsonnet
std.manifestYamlDoc(
{
x: [1, 2, 3, true, false, null,
"string\nstring\n"],
y: { a: 1, b: 2, c: [1, 2] },
},
indent_array_in_object=false)
```
```yaml
"x":
- 1
- 2
- 3
- true
- false
- null
- |
string
string
"y":
"a": 1
"b": 2
"c":
- 1
- 2
```
--------------------------------
### ImageMixin object in service.jsonnet
Source: https://jsonnet.org/articles/fractal.2.html
Defines common fractal-specific configuration for images, including project ID and service account key. Adds debugging and basic packages to aptPackages. This object is a variable and will not appear in the output.
```jsonnet
local ImageMixin = {
project_id: credentials.project,
account_file: "service_account_key.json",
// For debugging:
local network_debug = ["traceroute", "lsof", "iptraf", "tcpdump", "host", "dnsutils"],
aptPackages +: ["vim", "git", "psmisc", "screen", "strace" ] + network_debug,
},
```
--------------------------------
### std.manifestXmlJsonml without whitespace
Source: https://jsonnet.org/ref/stdlib.html
Converts a JsonML-encoded value to XML. The example shows the input and the resulting XML output (all on one line).
```jsonnet
std.manifestXmlJsonml([
'svg', { height: 100, width: 100 },
[
'circle', {
cx: 50, cy: 50, r: 40,
stroke: 'black', 'stroke-width': 3,
fill: 'red',
}
],
])
```
```xml
;
```
--------------------------------
### std.parseHex example
Source: https://jsonnet.org/ref/stdlib.html
Parses an unsigned hexadecimal integer from a string, case insensitive. std.parseHex("ff") yields 255.
```jsonnet
std.parseHex("ff")
```