Search code examples
jsonjsonnet

String Interpolation in Keys in Jsonnet


I'm wondering if it's possible to have string interpolation in keys when using jsonnet?

For example, I want to do something like this:

{
 std.format("Hello %03d", 12): "milk"
}

But it results in

STATIC ERROR: arith.jsonnet:2:5: expected token OPERATOR but got "."

I know the 'key' itself is valid, because if I don't use interpolation it works fine, i.e.

{
    "milk": std.format("Hello %03d", 12),
    "Hello 12": "milk"
}

generates:

{
  "Hello 12": "milk",
  "milk": "Hello 012"
}

It also looks like I can't use variables in keys, as they get resolved as just a string (not the variable's value) - any suggestions would be appreciated.


Solution

  • For computed field names, you need to wrap them with [] (see https://jsonnet.org/learning/tutorial.html#computed_field_names ), i.e. below will just work:

    {
     [std.format("Hello %03d", 12)]: "milk"
    }