如何以编程方式在 MarkLogic 的 XQuery 中创建 JSON?

How do I programmatically create JSON in XQuery in MarkLogic?

我需要在 MarkLogic 的 XQuery 中建立一个 JSON 节点。我知道我可以使用 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 在 XQuery 中构建 XML 节点。 JSON 个节点有类似的东西吗?

JSON 在 MarkLogic 中实现为 XML 数据模型的扩展。 MarkLogic 8 引入了 object-nodearray-nodenumber-nodeboolean-nodenull-node 测试和构造函数。因此,在 XQuery 中,您可以使用计算构造函数构建 JSON,就像使用 XML 一样。例如,

object-node { 
  "key" || fn:string(xdmp:random(100)): array-node { 1, 2, 3 }, 
  "another": object-node { "child":  text {'asdf'} },
  "lastButNotLeast": boolean-node { fn:true() }
}

将创建 JSON、

{
  "key47": [1, 2, 3],
  "another": {
    "child": "asdf"
  },
  "lastButNotLeast": true
}

旁白:在 JavaScript 中,您可以使用 JavaScript 语法将类似 JSON 的结构构建为 JavaScript 对象。您可以使用 xdmp.toJSON(). Most builtin functions that require a JSON node, however, will do this conversion automatically, such as xdmp.documentInsert().

将 JavaScript 对象转换为 JSON 节点