jsonnet

jsonnet conditional generation of a field


How can I get something like this working in jsonnet?

{
    if 1 == 1 then
      store: true
}

I get the below error when I run it with jsonnet:

STATIC ERROR: a.jsonnet:2:9-11: unexpected: if while parsing field definition

I would like to generate a json like this, just as an example, but while evaluating some conditions:

{
  "store": true
}

Solution

  • Below snippet implements conditional store_A and store_B fields, corresponding to val_A and val_B values, ab-using jsonnet [null] evaluated fieldname to remove it from being manifested

    local exp_val = 1;
    local val_A = 1;
    local val_B = 0;
    
    {
      [if val_A == exp_val then 'store_A']: true,
      [if val_B == exp_val then 'store_B']: true,
    }