-
-
Save emchateau/0b888b86b8572f6a8999 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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