JSON is a popular format for exchange of structured data on the web: it is specified in [RFC 7159]. This section describes facilities allowing JSON data to be processed using XSLT.
Note:
RFC7159 is taken as the definitive specification of JSON for the purposes of this document. The RFC explains its relationship with other JSON specifications such as [ECMA-404].
Note:
XPath 3.1 incorporates the functions defined in this
section. It also provides additional JSON capability, in the form of functions
parse-json
, json-doc
, and extensions to the
serialize
FO30 function. These facilities are incorporated in XSLT
3.0 only if the XPath 3.1 feature is supported. They depend on support for
arrays.
Given an XML structure that does not use the XML representation of JSON defined in
23.1 XML Representation of JSON, there are two practical ways to convert it
to JSON: either perform a transformation to the XML representation of JSON and then
call the xml-to-json
function; or transform it to JSON directly
by using custom template rules.
To assist with the second approach, a stylesheet is provided in B.2 Stylesheet for converting XML to JSON. This stylesheet includes a function
j:xml-to-json
which, apart from being in a different namespace, is
functionally very similar to the xml-to-json
function described in
the previous section. (It differs in doing less validation
of the input than the function specification requires, and in the details of how
special characters are escaped.)
The implementation of the function is exposed, using template
rules to perform a recursive descent of the supplied input, and the behavior of the
function can therefore be customized (typically by importing the stylesheet and
adding additional template rules) to handle arbitrary XML input.
The stylesheet is provided under the W3C software license for the convenience of
users. There is no requirement for any conformant XSLT processor to make this
stylesheet available. Processors may implement the
xml-to-json
function by invoking this stylesheet (adapted
to achieve full conformance), but there is no requirement to do so.