Format JSON Server Side

Mark_Didrikson
ServiceNow Employee
ServiceNow Employee

I am trying to format a JSON string for logging. I have a client script where I use JSON.stringify(content, null, 4) and I get a nice formatted JSON string.


Is there an equivalent function available server side?   Also I seem to be able to get server side is one long string with no formatting.

{"generalInfo":{"actionType":"SC","dependencyType":null,"env":"tec","filterOverride":null,"guid":"6851370928697643","jobType":"j","jobfamily":"TST_TST","numRecords":151,"objectIdentifier":null,"requestType":"CP","subActionType":"cancel","userId":"mark.didrikson","vendor":"serviceNow","workstation":null},

I want it to look like this:

{

      "generalInfo": {

              "actionType": "PDS",

              "dependencyType": null,

              "env": "tec",

              "filterOverride": null,

              "guid": "1424831054435801",

              "jobType": "s",

              "jobfamily": "TST_TS5",

              "numRecords": 10,

              "objectIdentifier": null,

              "requestType": "CP",

              "subActionType": "subOnHold",

              "userId": "mark.didrikson",

              "vendor": "serviceNow",

              "workstation": null

      },

6 REPLIES 6

Justin Abbott
Giga Guru

I'll typically log it out into one long string, as you mentioned above, and then throw it in JS Beautifier (Online JavaScript beautifier) for readability.


sumeet_n
Kilo Guru

Try this:



Assign the JSON string to a variable:



var x = <JSON String>;



Use JSON class to format it in a proper JSON object:



var obj = new JSON().decode(x);


I get this:



*** Script: JSON: [object Object]




var str = gs.getProperty('json_pretty');


var json_string = new JSON().decode(str);


gs.print('JSON: ' + json_string);


So if you just want to beautify the JSON string, there are many online tools available to beautify it.


Example: Online JSON Viewer



If you want to use this object further in the script, then you can follow the code I mentioned before and you can access the properties either by dot walking or by running a loop like below:


var str = gs.getProperty('json_pretty');


var json_string = new JSON().decode(str);


for(var x in json_string){


    gs.log(x + ' ' + json_string(x));


    //further usage of these key(x) value(json_string[x]) pairs


}



If you want to beautify this in server side and store it somewhere, then you need to use the same code above, only this time, usage would be to use appropriate condition, spaces/tabs and new lines to make it look good.