XQuery/Convert XML to JSON

From Wikibooks, open books for an open world
Jump to navigation Jump to search

You can use the JSON output method to convert XML to JSON format. (For an important note on this article, see https://stackoverflow.com/questions/48876292/how-to-use-the-xslt-xquery-serialization-namespace-to-export-to-json/.)

xquery version "3.0";

declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method "json";
declare option output:media-type "application/json";

let $test :=
  <!-- simple elements -->
  <!-- complex (nested) element -->
  <!-- duplicate elements -->
  <!-- attributes -->
  <iii a1="123" a2="456" a3="789"/>
  <!-- attributes with text content-->
  <jjj a1="123" a2="456" a3="789">JJJ</jjj>

return $test

Sample Output[edit | edit source]

    "aaa": "AAA",
    "bbb": "BBB",
    "ccc": "CCC",
    "ddd": {"eee": {"fff": {"ggg": "GGG"}}},
    "hhh": [
    "iii": {
        "a1": "123",
        "a2": "456",
        "a3": "789"
    "jjj": {
        "a1": "123",
        "a2": "456",
        "a3": "789",
        "#text": "JJJ"