2

I'm using eXist-db 4.7.0 and i want to store the result of a XQuery as JSON. Currently, i've got a XQuery that returns JSON using the serialisation options:

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 returns nice JSON content:

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

Now i want to store the resulting JSON directly into the DB. I've tried to replace the return $result clause by

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

but this stores the result as

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

Setting the MIME type to application/json didn't change anything:

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

What am i missing or doing wrong?

tohuwawohu
  • 13,268
  • 4
  • 42
  • 61

1 Answers1

3

An answer deleted by its owner (i will gladly accept it as soon as it's restored) led me on the right way: calling fn:serialize() on the $result solved the issue (see also the eXist-db blog on XQuery 3.1 support).

So, modifying the return clause as follows solved the issue:

return
    xmldb:store(
    '/db/services',
    'test1.json',
    serialize($result, map { 'method':'json'})
)
tohuwawohu
  • 13,268
  • 4
  • 42
  • 61