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="">

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

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

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

Java code to perform the transformation:

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

SchemaFactory schemaFactory = SchemaFactory.newInstance("");
Schema schema = schemaFactory.newSchema(new StreamSource(Test.class
ValidatorHandler validatorHandler = schema.newValidatorHandler();
validatorHandler.setErrorHandler(new __ErrorHandler());

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

JsonSaxReader reader = new JsonSaxReader();
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.

xslt4json.zip17.11 KB


Post new comment

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