Formatting Objects in Scripts for Readability
When outputting objects in logs or in print lines in Tryout for debugging purposes it can be useful to have them in a more easily human-readable format. Groovy has good native support for this with most data types (though note that there can be exceptions).
JsonBuilder.toPrettyString()
It is as simple as this one line of code in most cases:
new groovy.json.JsonBuilder( [ ... dataToVisualise ... ]).toPrettyString()
For example:
groovy
1// Find all "flow" events from the dialog history
2def allFlowEvents = []
3_.dialogHistory?.each { transaction ->
4 allFlowEvents << transaction.path.findAll { it.type.endsWith("Flow") }
5}
6
7// Write them to engine logs
8println new groovy.json.JsonBuilder(allFlowEvents).toPrettyString()
9
This code will output something like this:
json
1[
2 [
3 {
4 "metadata": {
5 "Set on Flow": "tracing_var"
6 },
7 "vertexName": "",
8 "vertexId": "f36a5ed0-2d4a-4a5a-872f-f223c73e2d58",
9 "flowFolder": "/Folder 1",
10 "changedSessionVariables": {
11
12 },
13 "name": "Normal flow",
14 "description": "",
15 "changedFlowVariables": {
16
17 },
18 "type": "raiseFlow",
19 "flowId": "95dd1117-9a42-4513-9730-6f11fc78dacb",
20 "flowName": "Normal flow",
21 "flowInstanceId": "bb705b2c-f2fd-4901-b4ca-33a86831c7fe"
22 },
23 {
24 "metadata": {
25 "Set on Flow": "tracing_var"
26 },
27 "vertexName": "",
28 "vertexId": "0df4a444-9447-4165-a7ac-7ded635943ae",
29 "aborted": false,
30 "description": "",
31 "type": "dropFlow",
32 "flowName": "Normal flow",
33 "flowInstanceId": "bb705b2c-f2fd-4901-b4ca-33a86831c7fe",
34 "flowFolder": "/Folder 1",
35 "stuck": false,
36 "changedSessionVariables": {
37
38 },
39 "name": "Normal flow",
40 "changedFlowVariables": {
41
42 },
43 "flowId": "95dd1117-9a42-4513-9730-6f11fc78dacb"
44 }
45 ]
46]
47
Whereas without this code, the output would have looked something like this:
json
103/02/2020 15:57:28 [Println]: [[[metadata:[Set on Flow:tracing_var], vertexName:, vertexId:f36a5ed0-2d4a-4a5a-872f-f223c73e2d58, flowFolder:/Folder 1, changedSessionVariables:[:], name:Normal flow, description:, changedFlowVariables:[:], type:raiseFlow, flowId:95dd1117-9a42-4513-9730-6f11fc78dacb, flowName:Normal flow, flowInstanceId:7313d738-aa20-4c69-bf15-7812316df1b0], [metadata:[Set on Flow:tracing_var], vertexName:, vertexId:0df4a444-9447-4165-a7ac-7ded635943ae, aborted:false, description:, type:dropFlow, flowName:Normal flow, flowInstanceId:7313d738-aa20-4c69-bf15-7812316df1b0, flowFolder:/Folder 1, stuck:false, changedSessionVariables:[:], name:Normal flow, changedFlowVariables:[:], flowId:95dd1117-9a42-4513-9730-6f11fc78dacb]]]
2