After we've got acquainted with a way to read existing JSON messages (see the Parsing JSON messages with JsonSlurper recipe) and create our own (see Constructing JSON messages with JsonBuilder recipe), we need to have the ability to modify the messages that flow through our system.
This recipe will show how straightforward it is to alter the content of a JSON document in Groovy.
Let's use the same JSON data located in the ui.json
file that we used in the Parsing JSON messages with JsonSlurper recipe.
import groovy.json.* def reader = new FileReader('ui.json') def ui = new JsonSlurper().parse(reader)
Since the data is actually just a nested structure, which consists of Maps, Lists and primitive data types, we can use the same API we would use for collections to navigate and change JSON data.
ui.items[0].type = 'panel' ui.items[0].title = 'Main Window' ui.items[0].remove('axes') ui.items[0].remove('series')
groovy.json.JsonOutput
class, which is designed specifically for that purpose. By using the static toJson
and prettyPrint
methods we can get an indented text version of the modified message:println JsonOutput.prettyPrint(JsonOutput.toJson(ui))
{ "items": [ { "title": "Main Window", "animate": true, "height": 270, "width": 319, "insetPadding": 20, "type": "panel" } ] }
As we are operating on a Map
, the code above does not do anything else but adding and removing Map
entries.
The toJson
method returns a String
with a compact version of the JSON data. The prettyPrint
method adds additional indentation spaces to any given JSON string.