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 :=
<root>
  <!-- simple elements -->
  <aaa>AAA</aaa>
  <bbb>BBB</bbb>
  <ccc>CCC</ccc>
  <!-- complex (nested) element -->
  <ddd>
     <eee>
        <fff>
           <ggg>GGG</ggg>
        </fff>
     </eee>
  </ddd>
  <!-- duplicate elements -->
  <hhh>HHH1</hhh>
  <hhh>HHH2</hhh>
  <hhh>HHH3</hhh>
  <hhh>HHH4</hhh>
  <!-- attributes -->
  <iii a1="123" a2="456" a3="789"/>
  <!-- attributes with text content-->
  <jjj a1="123" a2="456" a3="789">JJJ</jjj>
</root>

return $test

Sample Output[edit]

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