The extensions.groovy bundle includes a Groovy Builder which makes it easy to create JSON documents from Sling scripts. This code is inspired by the builder contained in Andres Almiray's json-lib project (http://json-lib.sourceforge.net/). However, Sling's builder is not compatible with the json-lib builder.
An instance of this class is available to all Groovy scripts as a variable named
A basic script looks like this:
This can be simplified by using
These examples are taken from the test case: http://svn.apache.org/viewvc/sling/trunk/bundles/commons/json/src/test/groovy/org/apache/sling/commons/json/groovy/JSONGroovyBuilderTest.groovy?view=markup.
The JSON output below is formatted for readability. Actual output will be compact.
Creating a Wrapper
json pseudo-method of
JSONGroovyBuilder produces an instance of
org.apache.sling.commons.json.JSONObject based on the parameters passed to it. If a different psuedo-method is called, the method name will be used to create a wrapper object. For example: