jsonnet icon indicating copy to clipboard operation
jsonnet copied to clipboard

Is it possible to interpolate nested object?

Open pombadev opened this issue 2 years ago • 4 comments

My jsonnet file looks like this.

local constants = {
  sys: {
    os: 'linux',
    arch: ['amd64', 'x86_64'],
  },
};

{
  prefix: '~/.local',
  packages: [
    {
      local version = '1.18',

      name: 'golang',
      version: version,
      file: 'go%(version)s.%(sys.os)s-%(sys.arch[0])s.tar.gz' % { version: version } + constants,
      description: 'The Go programming language.',
      url: 'https://dl.google.com/go/' + self.file,
      prebuild: "curl -LO '%(url)s'" % self,

      build: |||
        rm -rf %(prefix)s/go
        tar -C %(prefix)s -xzf %(file)s
      ||| % { prefix: $.prefix, url: $.packages[0].file },
    },
  ],
}

I'm trying to access nested field but get an error:

...
file: 'go%(version)s.%(sys.os)s-%(sys.arch[0])s.tar.gz' % { version: version } + constants,
...

Error:

RUNTIME ERROR: No such field: sys.os

Expected:

file: "go1.18.linux-amd64.tar.gz"

pombadev avatar Apr 09 '22 21:04 pombadev

Unfortunately, no. The format operator % / format function std.format do not perform full expression interpolation, they only look up the specified key in a flat object. This is the same as the Python 2 string-formatting % operator (https://docs.python.org/2/library/stdtypes.html#string-formatting-operations).

There was a related feature request from several years ago, #45, asking to add support for ES6 backtick strings (aka template literals).

(I'm aware this question was from a while ago, but perhaps having an answer will be useful for someone in the future)

johnbartholomew avatar Mar 06 '24 10:03 johnbartholomew

std.format supports nested objects: https://github.com/google/jsonnet/pull/1011 But syntax is limited to only objects, no array access.

CertainLach avatar Mar 06 '24 13:03 CertainLach

std.format supports nested objects: #1011

Oh, huh... that's interesting. I did not realize that. Thanks for the correction!

johnbartholomew avatar Mar 06 '24 14:03 johnbartholomew

Hmm... it looks like that feature was reverted: https://github.com/google/jsonnet/pull/1099

johnbartholomew avatar Mar 06 '24 14:03 johnbartholomew