Output JSON

Last modified by Raphaël Jakse on 2024/05/03 10:45

cogExample of how to generate JSON from a wiki page
Developed by


0 Votes
LicenseSimplified BSD License


To output JSON, you need to ensure that:

  • Nothing alters your output, including
  • You only render the specified content (and not all the menus, etc.) by using the plain.vm template - you can do this automatically by using the 'get' action or explicitly setting the template with 'xpage=plain'
  • the correct HTTP content-type is sent.

To avoid any altering including icon transformation, you need to write to the Response object directly.

In Velocity

In velocity, the #jsonResponse macro does all the work for you. Set the output=false parameter to avoid unnecessary parsing.

Consider the following page (assume it is page JsonHello in space JsonDemo):

{{velocity output="false"}}
    "greeting" : "Hello",
    "location": "World"

This should then be accessed via path /xwiki/bin/get/JsonDemo/JsonHello?outputSyntax=plain or /xwiki/bin/get/JsonDemo/JsonHello?xpage=plain&outputSyntax=plain

If you already have a JSON string / need more control, you can do something like this:

{{velocity wiki="false"}}
  #set($mylist = ['foo','bar'])
  #set($mymap = {"things": $mylist})

Make sure you disable wiki formatting with the wiki="false" parameter of the Velocity macro!

The $xcontext.setFinished(true) call ensures nothing will be written after the JSON data.

In Groovy

There's nothing like #jsonResponse in Groovy, so you will need to do it manually.

You can use JsonSlurper, or even manually import jsontool:

def jsontool = new org.xwiki.velocity.tools.JSONTool()
response.getWriter().write(jsontool.serialize(['alice': 2]))

Alternatively you can use the standard JSON libraries available to Groovy.


Get Connected