How to output JSON with Berlioz

Skills requiredXSLT, JSON
Time required (minutes)15
Intended audiencedevelopers
Difficultyeasy
Categoryfront-end

Objective

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.

Tutorial

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:

http://localhost:8099/ 

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:

/WEB-INF/xslt/json/default.xsl

Step 3: Add Aeson namespace

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

Aeson uses the XML namespace http://pageseeder.org/JSON for its elements and attributes, you need to ensure that you XSLT module includes that namespace declaration:

<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xs="http://www.w3.org/2001/XMLSchema"
                xmlns:json="http://pageseeder.org/JSON"
                exclude-result-prefixes="#all">

Note

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

Note

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:

http://localhost:8099/home.json 

{}

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}" />
</xsl:template>

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

And check that the output is

{"greeting": "Hello World!"}

Created on , last edited on