Arjun
Arjun

Reputation: 475

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
}

Upvotes: 6

Views: 12900

Answers (2)

Andrei Titov
Andrei Titov

Reputation: 1668

I believe it's also possible to accomplish this using jsonnet "object composition operator" +, like this:

{
  "otherProperty": 1,
} + (if yourCondition then { "store": true } else {})

If yourCondition is true - source object will be merged with another object, where the needed prop exists, and if not - it will be merged with an empty object, making no change to the source.
You can also read the official docs about this here.

Upvotes: 0

jjo
jjo

Reputation: 3020

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,
}

Upvotes: 11

Related Questions