Re: [xsl] json to json transformation

Subject: Re: [xsl] json to json transformation
From: "Michael Kay mike@xxxxxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Fri, 15 Mar 2019 12:31:13 -0000
>  I tried above XSLT transformation with Saxon, and it produces following,
>  {
>   "name":"Mukul Gandhi",
>   "address": {
>     "street1":"xyz",
>     "street2":"maddison avenue",
>     "country":"C1"
>    },
> ...
> The order of keys in above JSON output is not same as the input JSON. In the
JSON, I wanted fName and lName pair to be replaced by the 'name' key, and
wished that order of keys in JSON was preserved.
> I think, with XPath 3.1 maps the ordering of keys has no relevance, and from
that point of view your XPath 3.1 map solution above is fine. But if order of
keys in the JSON need to be retained, is something like JSON to XML & back to
JSON again the only way ? I guess, Mike's paper discusses issues including the
previous point in a general way.

The functions json-to-xml() and xml-to-json() are both defined to retain
order; however parse-json() produces maps that retain no information about the
original order. As with attributes in XML, the order of entries in a JSON map
is not supposed to have any significance; however I've certainly seen cases
where there's an order that greatly aids readability. Not just for cases like
this where (street1, street2, country) makes more sense than (street2,
country, street1), but also cases where one of the entries in the map is very
large and the others are small; you want the small ones to come first, as with
XML attributes vs content.

Saxon therefore provides

<xsl:output method="json"
    saxon:property-order="name address
                                         street1 street2 country"/>

to control the serialization order when serializing maps as JSON text.

Michael Kay

Current Thread