How to Transform JSON using XSLT

There are some debates about declining use of XML and rising use of JSON. Some people love XML, some people love JSON. I love SAX: assuming SAX serializer/deserializers exist, anything can be treated as XML.

For example, you can write XSLT stylesheets transforming JSON: JSON SAX deserializer was already created by me in my previous article "How to Convert JSON to XML using ANTLR" and JSON SAX serializer is fairly easy to write. Once you have all that, you can transform JSON using XSLT:

{
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": "10021"
     },
     "phoneNumber": [
         { "type": "home", "number": "212 555-1234" },
         { "type": "fax", "number": "646 555-4567" }
     ]
}
<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" omit-xml-declaration="no" indent="no" encoding="UTF-8"/>

    <xsl:template priority="-9" match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="field[@name='firstName']/string[.='John']">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:text>Peter</xsl:text>
        </xsl:copy>
    </xsl:template>
    
</xsl:stylesheet>

Java code to perform the transformation:

JsonSaxWriter writer = new JsonSaxWriter(new FileOutputStream(outputFile));

SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = schemaFactory.newSchema(new StreamSource(Test.class
        .getResourceAsStream("json.xsd")));
ValidatorHandler validatorHandler = schema.newValidatorHandler();
validatorHandler.setErrorHandler(new __ErrorHandler());
validatorHandler.setContentHandler(writer);

TransformerHandler transformerHandler = ((SAXTransformerFactory)TransformerFactory.newInstance()).newTransformerHandler(new StreamSource(xsltFile));
transformerHandler.setResult(new SAXResult(validatorHandler));

JsonSaxReader reader = new JsonSaxReader();
reader.setContentHandler(transformerHandler);
reader.parse(new InputSource(inputFile.toString()));

This is simple SAX pipeline, coded in reverse order, w/ SAX event flow like:
JsonSaxReader->TransformerHandler->ValidatorHandler->JsonSaxWriter. Notice, XSD validation is purely optional, it is just to double-check output of XSLT.

AttachmentSize
xslt4json.zip17.11 KB

Comments

How to Transform JSON using XSLT

No matter if some onee searches for his essential thing, therefore he/she desires to be available that
in detail, therefore thatt thing iis mainained over here.

Post new comment

The content of this field is kept private and will not be shown publicly.