Quantcast
Channel: GerixSoft - JSON
Viewing all articles
Browse latest Browse all 2

How to Transform JSON using XSLT

$
0
0

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

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images