Skip to content

Instantly share code, notes, and snippets.

@emchateau
Forked from joewiz/json-xml.xqm
Last active August 29, 2015 14:16
Show Gist options
  • Save emchateau/0b888b86b8572f6a8999 to your computer and use it in GitHub Desktop.
Save emchateau/0b888b86b8572f6a8999 to your computer and use it in GitHub Desktop.
xquery version "3.1";
(: Utility functions for JSON as derived via XQuery 3.1's parse-json and json-doc functions.
: See http://www.w3.org/TR/xpath-functions-31/#json :)
module namespace ju = "http://joewiz.org/ns/xquery/json-util";
declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization";
(: Get the data type for a piece of JSON data :)
declare function ju:json-data-type($json) {
if ($json instance of array) then 'array'
else if ($json instance of map) then 'map'
else if ($json instance of xs:string) then 'string'
else if ($json instance of xs:double) then 'number'
else if ($json instance of xs:boolean) then 'boolean'
else if (empty($json)) then 'null'
else error(xs:QName('ERR'), 'Not a known data type for json data')
};
(: Transform JSON into intermediate XML format described at http://www.w3.org/TR/xslt-30/#json :)
declare function ju:json-to-xml($json) {
let $data-type := ju:json-data-type($json)
return
element {QName('http://www.w3.org/2013/XSL/json', $data-type)} {
if ($data-type = 'array') then
for $array-member in $json?*
let $array-member-data-type := ju:json-data-type($array-member)
return
element {$array-member-data-type} {
if ($array-member-data-type = ('map', 'array')) then
ju:json-to-xml($array-member)/node()
else
$array-member
}
else if ($data-type = 'map') then
map:for-each-entry(
$json,
function($object-name, $object-value) {
let $object-value-data-type := ju:json-data-type($object-value)
return
element {$object-value-data-type} {
attribute key {$object-name},
if ($object-value-data-type = ('map', 'array')) then
ju:json-to-xml($object-value)/node()
else
$object-value
}
}
)
else (: if ($type = ('string', 'number', 'boolean', 'null')) then :)
$json
}
};
(: Serialize with indentation :)
declare function ju:serialize-json($json) {
let $serialization-parameters :=
<output:serialization-parameters>
<output:method>json</output:method>
<output:indent>yes</output:indent>
</output:serialization-parameters>
return
serialize($json, $serialization-parameters)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment