zorbajsoniq

JSONiq console.log or print


Is it possible to print to console for debugging purposes in a JSONiq/Zorba script?

e.g.

declare function utils:lowerCaseKey($obj as item) as item{
   print($obj)
  {|
    for $k in  distinct-values(keys( $obj ))
    return { lower-case($k) : $obj.$k } (: note the ',' to create a sequence :)
  |}
};

Solution

  • Yes: the trace function serves this purpose. It can be called on any expression of which one needs to see the output, together with a label of your choice.

    declare function utils:lowerCaseKey($obj as item) as item
    {
      {|
        for $k in  distinct-values(keys( trace($obj, "obj") ))
        return { lower-case($k) : $obj.$k }
        (: note the ',' to create a sequence :)
      |}
    };
    

    This will cause output such as:

    obj [1]: { "foo" : "bar" }
    obj [2]: { "foo" : "bar2" }
    

    Where exactly (on the command line, in a log file...) this output is sent should be documented in each engine. Zorba will by default output to stderr.

    Note that this is a declarative language, so that trace behaves differently than print. Some expressions may be optimized away if not needed, in which case it generates no trace. For example,

    (1, trace(2, "foo"))[1]
    

    may not generate a trace. Likewise, the order in which traces are generated may be implementation-dependent, because JSONiq, like XQuery, leaves each engine the freedom how to evaluate best an expression, as long as its results conform to the specification.