4

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
}
Arjun
  • 385
  • 5
  • 17
  • Do you also want to conditionally create the field rather than just its value ? If the latter something like `{ store: 1 == 1 }` or `{ store: if 1 == 1 then "TRUE" else "FALSE" }` would do it. If you need the field itself to be conditionally present (as suggested by the question's title), it gets a bit more complex. – jjo Oct 20 '20 at 14:44
  • Thank you for the response. I need the field itself to be conditional present. – Arjun Oct 20 '20 at 14:48

1 Answers1

9

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,
}
Erick Mwazonga
  • 1,020
  • 12
  • 25
jjo
  • 2,595
  • 1
  • 8
  • 16