jsonnet

How to return a local object from a function in jsonnet?


I am working with jsonnet for the first time today. My IDE is Visual Studio Code 1.91.1, and I have the extension Jsonnet Language Server v0.6.1 from Grafana installed.

This code does not exhibit any errors:

// my-file.libsonnet

function(params) {
  hello: "world",
}

However, I would like to store the object as a local, so that I have the ability to do other things with it before returning.

Based on what I've read, I expected this code to work:

// my-file.libsonnet

function(params) {
  local myObject = {
    hello: "world",
  };
  myObject
}

However, there is an error at the semicolon that says Expected a comma before next field. So I tried replacing the semicolon with a comma:

// my-file.libsonnet

function(params) {
  local myObject = {
    hello: "world",
  },
  myObject
}

This results in an error at the final curly brace that says Expected token OPERATOR but got "}". I do not understand what this means.

All suggestions are appreciated.


Solution

  • The issue is that those braces in func() {} construct are "expecting" a { key: value } structure, as e.g. { ret: myObject } likely not what you want to return.

    Given that you want to return the "full object" you local-ly built above, it'd be matter of just returning it naked, i.e.:

    function(params)
      local myObject = {
        hello: 'world',
      };
      myObject
    

    Note also the use of ; just after the local construct.