XSLT - Generating JSON Output with XSLT

As web development has evolved, JSON (JavaScript Object Notation) has become the most widely used format for exchanging data between applications, especially in RESTful APIs, web services, and modern JavaScript frameworks. Many organizations still store their information in XML because of its structured nature and compatibility with enterprise systems. XSLT provides an efficient way to transform XML into JSON, allowing existing XML-based systems to communicate seamlessly with applications that expect JSON data.

XSLT was originally designed to transform XML into other XML documents, HTML pages, or plain text. Since JSON is essentially text with a specific structure, XSLT can also generate JSON by carefully formatting the output. Developers create templates that extract XML data and arrange it according to JSON syntax, including objects, arrays, property names, values, commas, quotation marks, and nested structures.

Why Convert XML to JSON?

Many modern applications no longer consume XML directly. Instead, they rely on JSON because it is lightweight, easy to read, and supported natively by JavaScript. Converting XML into JSON enables organizations to:

  • Integrate legacy XML systems with modern web applications.

  • Develop REST APIs that return JSON responses.

  • Exchange data with mobile applications.

  • Simplify client-side data processing.

  • Improve compatibility with cloud-based platforms.

For example, an XML file containing product information can be transformed into JSON before being sent to an e-commerce website or mobile shopping application.

Sample XML Document

<products>
    <product>
        <id>101</id>
        <name>Laptop</name>
        <price>65000</price>
    </product>
    <product>
        <id>102</id>
        <name>Mouse</name>
        <price>800</price>
    </product>
</products>

Desired JSON Output

{
  "products": [
    {
      "id": "101",
      "name": "Laptop",
      "price": "65000"
    },
    {
      "id": "102",
      "name": "Mouse",
      "price": "800"
    }
  ]
}

The XSLT stylesheet reads each product element and produces JSON text with correctly formatted objects and arrays.

Setting the Output Method

Since JSON is plain text rather than XML, the stylesheet typically specifies the output method as text.

Example:

<xsl:output method="text" encoding="UTF-8"/>

This tells the XSLT processor not to generate XML tags but instead produce plain text that follows JSON syntax.

Creating JSON Objects

A JSON object consists of key-value pairs enclosed within curly braces.

Example:

{
  "name": "Laptop",
  "price": "65000"
}

In XSLT, text values and XML element values are combined to create these JSON properties.

Example:

<xsl:text>"name":"</xsl:text>
<xsl:value-of select="name"/>
<xsl:text>"</xsl:text>

The output becomes:

"name":"Laptop"

Creating JSON Arrays

JSON arrays store multiple objects inside square brackets.

Example:

[
  {
    "id": "101"
  },
  {
    "id": "102"
  }
]

An XSLT loop processes each XML element one after another.

Example:

<xsl:for-each select="products/product">

Each iteration generates one JSON object.

Managing Commas Between Objects

One of the biggest challenges when generating JSON is placing commas correctly between objects while avoiding an extra comma after the final object.

Example of incorrect JSON:

[
  {"id":"101"},
  {"id":"102"},
]

The extra comma makes the JSON invalid.

XSLT solves this using the position() and last() functions.

Example:

<xsl:if test="position()!=last()">
    <xsl:text>,</xsl:text>
</xsl:if>

This adds commas only between objects.

Handling Nested XML Structures

Many XML documents contain nested elements.

Example:

<customer>
    <name>John</name>
    <orders>
        <order>
            <id>501</id>
        </order>
        <order>
            <id>502</id>
        </order>
    </orders>
</customer>

The JSON output becomes:

{
  "name": "John",
  "orders": [
    {
      "id": "501"
    },
    {
      "id": "502"
    }
  ]
}

XSLT templates process each nested level independently to preserve the hierarchical structure.

Working with XML Attributes

XML attributes can also be converted into JSON properties.

XML:

<employee id="E101">
    <name>David</name>
</employee>

JSON:

{
  "id": "E101",
  "name": "David"
}

The attribute value is retrieved using:

<xsl:value-of select="@id"/>

Handling Special Characters

JSON requires quotation marks, backslashes, and control characters to be escaped properly. If XML data contains these characters, the generated JSON must remain valid.

Example:

XML:

<name>John "Smith"</name>

Proper JSON:

{
  "name": "John \"Smith\""
}

Developers often include additional templates or functions to escape special characters correctly.

Using XSLT 3.0 Features

XSLT 3.0 introduced native support for JSON serialization, making JSON generation much easier than manually constructing text.

Some processors allow direct creation of maps and arrays, which are automatically serialized into valid JSON. This reduces errors related to commas, quotation marks, and formatting while making stylesheets more concise and maintainable.

Advantages of Generating JSON with XSLT

  • Reuses existing XML data without modifying the original source.

  • Simplifies integration with modern web and mobile applications.

  • Eliminates the need for separate XML-to-JSON conversion programs.

  • Supports automated data transformation pipelines.

  • Maintains a clear separation between source data and output format.

  • Enables enterprise systems to interact with RESTful services.

  • Reduces development effort when modernizing legacy applications.

Limitations

  • Manual JSON generation in XSLT 1.0 can become complex for deeply nested documents.

  • Incorrect comma placement or missing quotation marks can produce invalid JSON.

  • Escaping special characters requires careful handling.

  • Large transformations may require performance optimization.

  • Advanced JSON features are easier to implement in XSLT 3.0 than in earlier versions.

Best Practices

  • Always validate the generated JSON using a JSON validator.

  • Use method="text" when manually generating JSON.

  • Carefully handle commas between objects and arrays.

  • Escape special characters properly.

  • Keep templates modular for easier maintenance.

  • Use XSLT 3.0 JSON serialization features whenever available.

  • Test transformations with both small and large XML documents to ensure correctness and performance.

Conclusion

Generating JSON output with XSLT enables organizations to bridge the gap between traditional XML-based systems and modern applications that rely on JSON. By transforming structured XML into well-formed JSON, developers can integrate legacy databases, enterprise software, web services, and mobile applications without changing the original data source. While manual JSON generation requires careful attention to formatting and syntax, modern versions of XSLT provide built-in features that simplify the process, making XSLT a powerful tool for data transformation in contemporary software development.