Jsonnet - Getting Started

Sometimes it is useful to generate output that is not in JSON format. You can do this by writing Jsonnet code which evaluates to a string containing whatever your desired format is. When executed with jsonnet -S or jsonnet --string jsonnet will manifest the string result as plain text rather than a JSON-formatted string.

// ini_output.jsonnet
std.manifestIni({
  sections: {
    main: {
      host: "127.0.0.1",
      port: "9000",
    },
    database: {
      path: "/var/data",
    },
  },
})

When executed using jsonnet -S ini_output.jsonnet, this will output the generated INI formatted text directly.

$ jsonnet -S ini_output.jsonnet
[database]
path = /var/data
[main]
host = 127.0.0.1
port = 9000

The Jsonnet commandline tool has a special mode for generating multiple JSON files from a single Jsonnet file. This can be useful if you want to avoid writing lots of small Jsonnet files, or if you want to take advantage of cross-references and interdependencies between the files. The idea is to create a single JSON structure, the top level of which defines the various files:

// multiple_output.jsonnet
{
  "a.json": {
    x: 1,
    y: $["b.json"].y,
  },
  "b.json": {
    x: $["a.json"].x,
    y: 2,
  },
}

When executed using jsonnet -m <dir>, this will write the generated JSON to files a.json and b.json in the given directory, instead of the whole thing being written to stdout. In order to integrate nicely with build tools like make, the files are not touched if they already contain the given content. To stdout is printed the list of target files, one per line. This makes it easy to drive other tools that operate on the JSON files, e.g. via xarg.

$ jsonnet -m . multiple_output.jsonnet
a.json
b.json
$ cat a.json
{
   "x": 1,
   "y": 2
}
$ cat b.json
{
   "x": 1,
   "y": 2
}

Unlike JSON, YAML can represent several objects in the same file, separated by ---. The Jsonnet commandline parameter -y causes the tool to expect the Jsonnet execution to yield an array. Config designed for this mode typically looks like this: It then outputs that array as a sequence of JSON documents separated by ---, which any YAML parser will interpret as a YAML stream.

// yaml_stream.jsonnet
local
  a = {
    x: 1,
    y: b.y,
  },
  b = {
    x: a.x,
    y: 2,
  };

[a, b]

When executed using -y, this will output that array as a sequence of JSON documents separated by --- and terminated with .... Any YAML parser should interpret this as a YAML stream (people have reported broken parsers, so try it out first).

$ jsonnet -y yaml_stream.jsonnet
---
{
   "x": 1,
   "y": 2
}
---
{
   "x": 1,
   "y": 2
}
...