我尝试了几种不同的方法,但似乎只有一个自定义函数可以解决问题:
xquery version "1.0-ml";
declare namespace fx = "http://www.functx.com";
declare function fx:repeat-string
( $stringToRepeat as xs:string? ,
$count as xs:integer ) as xs:string {
string-join((for $i in 1 to $count return $stringToRepeat),
'')
} ;
declare function local:stringify($nodes, $indent) {
local:stringify($nodes, $indent, 0)
};
declare function local:stringify($nodes, $indent, $level) {
let $indent-string := fx:repeat-string(" ", $indent * $level)
for $node in $nodes
return (
$indent-string
|| (
if (name($node) != "" and not($node/.. instance of array-node())) then
(""" || name($node) || "": ")
else ""
) || (
typeswitch ($node)
case object-node() return (
"{ " || string-join(local:stringify($node/node(), $indent, $level + 1), ", ") || " " || $indent-string || "}"
)
case array-node() return (
"[ " || string-join(local:stringify($node/node(), $indent, $level + 1), ", ") || " " || $indent-string || "]"
)
case text() return (
""" || replace(replace(replace($node, " ", "\\n"), " ", "\\r"), """, '\\"') || """
)
default return xdmp:quote($node)
)
)
};
let $json := object-node{
"text": "abc",
"number": 1,
"boolean": true(),
"null": null-node{},
"array": array-node{
"abc",
1,
true(),
null-node{},
object-node{ "foo": "bar "'mitswa" }
},
"object": object-node{
"text": "abc",
"number": 1,
"boolean": true(),
"null": null-node{},
"array": array-node{
"abc",
1,
true(),
null-node{},
object-node{ "foo": "bar" }
}
}
}
return (
xdmp:quote($json, map:entry("indentUntyped", "yes")),
xdmp:to-json-string($json),
xdmp:javascript-eval("JSON.stringify(json, null, 2);", map:entry("json", $json)),
local:stringify($json, 2)
)
HTH!