Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically create JSON in XQuery in MarkLogic?

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?

like image 847
Justin Makeig Avatar asked May 17 '16 21:05

Justin Makeig


1 Answers

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().

like image 91
Justin Makeig Avatar answered Sep 18 '22 20:09

Justin Makeig