JSON results
Monday, 27 October 2014 · 2 messages
TD
Thomas Daly27 Oct 2014 21:29 #
Hello,
I'm trying to construct a query that will return the title and ID from a set of records, but instead of XML results I'd prefer JSON. I'd like the results to be in the following format:
[
['id': 'value1', 'title': 'Title1'],
['id': 'value2', 'title': 'Title2'],
['id': 'value3', 'title': 'Title3']
]
I understand I'd need to use the JSON module, but I'm having trouble getting the results into the right format.
This is what I have so far:
XQUERY for $poem in collection("lk")
let $id := fn:string($poem/poem/@uuid)
let $title := $poem/poem/title/text()
order by $title
return (<id>{$id}</id>, <title>{$title}</title>)This returns the XML, but does anyone know how to convert into the desired JSON format?
Many thanks
CG
Christian Grün27 Oct 2014 21:40 #
Hi Thomas,
the JSON Module will help you here [1].
With XQuery 3.1, arrays will get part of the core language [2]. With the latest snapshot, you can create JSON as follows:
declare option output:method 'json';
[
map { 'id': 'value1', 'title': 'Title1' },
map { 'id': 'value2', 'title': 'Title2' },
map { 'id': 'value3', 'title': 'Title3' }
]Your feedback on the latest extensions are welcome,
Christian
[1] http://docs.basex.org/wiki/JSON_Module
[2] http://docs.basex.org/wiki/XQuery_3.1
Quoted text · Thomas Daly · 28 lines
On Mon, Oct 27, 2014 at 9:29 PM, Thomas Daly <thomas.daly at live.com> wrote: > Hello, > > I'm trying to construct a query that will return the title and ID from a set > of records, but instead of XML results I'd prefer JSON. > I'd like the results to be in the following format: > > [ > ['id': 'value1', 'title': 'Title1'], > ['id': 'value2', 'title': 'Title2'], > ['id': 'value3', 'title': 'Title3'] > ] > > I understand I'd need to use the JSON module, but I'm having trouble getting > the results into the right format. > This is what I have so far: > > XQUERY for $poem in collection("lk") > let $id := fn:string($poem/poem/@uuid) > let $title := $poem/poem/title/text() > order by $title > return (<id>{$id}</id>, <title>{$title}</title>) > > This returns the XML, but does anyone know how to convert into the desired > JSON format? > > Many thanks >
Written for BaseX 7.9. BaseX may have changed since: please check the current documentation.
⚡Generated with XQuery