首页 > 解决方案 > 将 xquery 结果存储为 json

问题描述

我正在使用 eXist-db 4.7.0,我想将 XQuery 的结果存储为 JSON。目前,我有一个使用序列化选项返回 JSON 的 XQuery:

xquery version "3.1";

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare namespace json = "http://www.json.org";
declare option output:method "json";
declare option output:media-type "application/json";

let $result as node() := element root {
    attribute json:array {"yes"},
    element data {
        attribute at1 {"1"},
        attribute at2 {"1"},
        element data1 {
            "test3"
        }
    }
}

return
    $result

whichs 返回不错的 JSON 内容:

[
    {
        "data": {
            "at1": "1",
            "at2": "1",
            "data1": "test3"
        }
    }
]

现在我想将生成的 JSON 直接存储到数据库中。我试图return $result

return
    xmldb:store (
        '/db/services',
        'test1.json',
        $result
    )

但这将结果存储为

<root xmlns:json="http://www.json.org" json:array="yes">
    <data at1="1" at2="1">
        <data1>test3</data1>
    </data>
</root>

将 MIME 类型设置为application/json并没有改变任何内容:

return xmldb:store(
    '/db/services',
    'test1.json',
    $result,
    'application/json'
)

我错过了什么或做错了什么?

标签: jsonserializationexist-db

解决方案


一个被其所有者删除的答案(我很乐意在它恢复后立即接受它)引导我走上正确的道路:调用fn:serialize()$result解决的问题(另请参阅关于 XQuery 3.1 支持的 eXist-db 博客)。

因此,修改 return 子句如下解决了这个问题:

return
    xmldb:store(
    '/db/services',
    'test1.json',
    serialize($result, map { 'method':'json'})
)

推荐阅读