I need to build up a JSON node in XQuery in MarkLogic. I know that I can use xdmp:unquote()
to parse from a string into a node()
. However, I’d like to build the JSON programmatically, without ugly string concatenation. I can use computed element constructors to build XML nodes in XQuery. Is there something similar for JSON nodes?
JSON is implemented in MarkLogic as an extension to the XML data model. MarkLogic 8 introduces object-node
, array-node
, number-node
, boolean-node
, and null-node
tests and constructors. Thus, in XQuery you can build JSON with computed constructors, just like you would with XML. For example,
object-node {
"key" || fn:string(xdmp:random(100)): array-node { 1, 2, 3 },
"another": object-node { "child": text {'asdf'} },
"lastButNotLeast": boolean-node { fn:true() }
}
will create the JSON,
{
"key47": [1, 2, 3],
"another": {
"child": "asdf"
},
"lastButNotLeast": true
}
Aside: In JavaScript you can build JSON-like structures as JavaScript objects using JavaScript syntax. You can convert a JavaScript object into a JSON node using xdmp.toJSON()
. Most builtin functions that require a JSON node, however, will do this conversion automatically, such as xdmp.documentInsert()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With