Skip to content

Instantly share code, notes, and snippets.

@jmakeig
Created December 1, 2016 19:21
Show Gist options
  • Select an option

  • Save jmakeig/f88cfdc5798680a325895eb43ef1cd63 to your computer and use it in GitHub Desktop.

Select an option

Save jmakeig/f88cfdc5798680a325895eb43ef1cd63 to your computer and use it in GitHub Desktop.
Pretty print JSON nodes from XQuery in MarkLogic (>=8)
(: NOTE: In a production system you should amp json:stringify to avoid arbitrary JavaScript execution. :)
declare function json:stringify($json as node(), $spaces as xs:int) as xs:string? {
xdmp:javascript-eval("JSON.stringify($json.toObject(), null, $spaces)", ('$json', $json, '$spaces', $spaces))
};
declare function json:stringify($json as node()) as xs:string? {
json:stringify($json, 2)
};
let $node := xdmp:unquote('["B", "B"]')
let $node := <asdf/> (: returns empty-sequence() :)
let $node := xdmp:unquote('{"a": "A", "b": ["B", "B"]}')
return json:stringify($node)
(:
=>
'
{
"a": "A",
"b": [
"B",
"B"
]
}
'
:)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment