0

Given the following jsonnetfile:

{
  expression: self.result,
  result: 3 > 1,
}

That evaluates to this:

{
   "expression": true,
   "result": true
}

Is there a way to convert the expression to string before evaluation? The desired result would be the following:

{
   "expression": "3 > 1",
   "result": true
}
hillsprig
  • 307
  • 5
  • 12

1 Answers1

2

As jsonnet doesn't support eval()- alike expressions, the only way really is to load such file as text with importstr() (then conveniently parse it as YAML¹), also with import() to get it parsed as jsonnet, then "merge" both objects to cherry-pick fields from each one.

Below is a possible approach for the above, of course, it could be generalized for more "complex" root object structure, but it's enough to show the approach.

Note that your original jsonnetfile is saved as foo.yaml, but with expression and result fields swapped (as I think this is your intent)

input (foo.yaml)

{
  expression: 3 > 1,  
  result: self.expression,
}

code

local asYAML = std.parseYaml(importstr 'foo.yaml');
local asJsonnet = import 'foo.yaml';

{
  expression: asYAML.expression,
  result: asJsonnet.result,
}

output

{
   "expression": "3 > 1",
   "result": true
}

¹ Note that loading jsonnet as YAML will only support a subset of jsonnet, as YAML parser may interfere with other language expressions

jjo
  • 2,595
  • 1
  • 8
  • 16
  • 1
    Awesome, and yes you guessed the intent correctly. It was just flipped in the example. Now to the harder part. Getting the non-technical people to write the expressions in a limited YAML-file and importing it :) Thanks again! – hillsprig May 27 '22 at 22:26