How to output JSON with Berlioz

Skills requiredXSLT, JSON
Time required (minutes)15
Intended audiencedevelopers


Berlioz can generate different kind of outputs, including HTML for end-users, XML and JSON.

In this tutorial, we're going to setup the home service to return the greeting as JSON.


Step 1: Berlioz base

Download  and setup Berlioz base from Github . Make sure that you can get Berlioz base running.

You should be able to see the home page at:


Step 2: Locate XSLT

In order for Berlioz to generate JSON, we need to specify how the raw XML output from the service will be transformed into JSON. This is done in XSLT.

Since Berlioz base follows the standard file layout, you can edit the following file:


Step 3: Add Aeson namespace

Berlioz uses Aeson to specify how the XML should be transformed into JSON.

Aeson uses the XML namespace for its elements and attributes, you need to ensure that you XSLT module includes that namespace declaration:

<xsl:stylesheet version="2.0"


Berlioz base is already configured to include this declaration. But if you create other XSLT modules, make sure that the namespace declaration is present.

Step 4: Define output type

Then we need to ensure that our XSLT module will output the correct type. In XSLT this is done using the <xsl:output>  element.

For Aeson, we are generated XML but the intended mediatype if JSON. Berlioz will pick it up and will automatically convert the XML events into JSON output.

<!-- JSON output via XML -->
<xsl:output method="xml" media-type="application/json"/>


Berlioz base is already configured to include this top level element and it only needs to be declared in you principal XSLT module.


Step 5: Create template

So far, we've only been making sure that Berlioz is ready to output JSON, and if you're starting from Berlioz base, there wasn't much to do! Now we are going to create a template to output JSON.

Before we update the XSLT, Berlioz will return an empty JSON object:



The raw service output can be seen at: http://localhost:8099/home.src 

We're going to insert the template below to transform the raw output into JSON

<!-- Match service 'home' -->
<xsl:template match="root[@service='home']">
  <!-- Return an object with property 'greeting' -->
  <json:object greeting="{//greeting}" />

Now go to: http://localhost:8099/home.json 

And check that the output is

{"greeting": "Hello World!"}

Created on , last edited on