Hakan Baba
Hakan Baba

Reputation: 2035

How to printf in jsonnet?

Is there a way to print the objects in jsonnet? This is for debugging purposes mainly.

I am using error to print the objects but that terminates the program execution.

local obj = [
{
  myKey: 2,
}];
error 'Printing' + std.toString(obj)

Outputs:

RUNTIME ERROR: Printing[{"myKey": 2}]
    snippet:6:1-37  

A better way to do this ?

Upvotes: 7

Views: 10483

Answers (3)

sbarzowski
sbarzowski

Reputation: 2991

[obsolete, see other answers]

At the moment (as of jsonnet 0.10) unfortunately no. There are plans to include it in a future release (issue here: https://github.com/google/jsonnet/issues/130).

People use errors (like you have shown in the code) or modify the code to output just the part they want (how handy it is depends on how you structured your code).

Upvotes: 1

jjo
jjo

Reputation: 3020

To followup on Dave Cunningham's answer, std.trace() is available since 0.11.0, it behaves like a "hook in the middle", where it's 1st argument is the string you want to show, 2nd is what you want to return.

Using it for the provided example:

$ cat foo.jsonnet
local obj = [
{
    myKey: 2,
}];
std.trace("obj content: %s" % [obj], obj)

$ jsonnet foo.jsonnet 
TRACE: foo.jsonnet:5 obj content: [{"myKey": 2}]
[
   {
      "myKey": 2
   }
]

Upvotes: 6

Dave Cunningham
Dave Cunningham

Reputation: 51

For posterity, OP was kind enough to contribute a new function to solve this problem: std.trace("message", rest).

Upvotes: 2

Related Questions