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?
Asked
Active
Viewed 1,999 times
6

Justin Makeig
- 2,097
- 15
- 29
-
Much more a MarkLogic question than a generic XQuery question. The way one did this in, say, BaseX would be different. ā Charles Duffy May 17 '16 at 21:27
-
Yup. Thanks. I've updated the title and description to reflect this. ā Justin Makeig May 17 '16 at 22:19
1 Answers
8
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()
.

Justin Makeig
- 2,097
- 15
- 29