With the rapid increase in REST based web service interfaces in the technology world, I get more and more questions around how to deal with REST services and the increasingly popular response format of JSON.
ServiceNow makes it pretty easy to handle JSON strings. In fact, if you have the JSON Web Service plugin enabled on your instance, you will have access to a nifty little Script Include called “JSONParser”.
JSONParser will take a JSON string and convert it to a Javascript Object. This is handy if you want to query different parts of the JSON string or reaction to a part of the response in a certain way.
Here is an example that takes a JSON string that contains information for a hat and a shoe and stores that information in a Javascript Object:
1 2 3 4 5 6 7 8 9 10 11 12 13 | //JSON String Representation of Clothing items var jsonString = '{"shoe":{"make":"Nike","model":"Air Jordan","size":"13"},"hat":{"type":"cap","size":"7.25","condition":"new"}}'; //JSONParser Script Include is available with the JSON Web Service plugin var parser = new JSONParser(); var parsed = parser.parse(jsonString); //Print different parts of the response gs.log("Shoe Size: " + parsed.shoe.size); gs.log("Hat Size: " + parsed.hat.size); //Print out the entire Javascript Object JSUtil.logObject(parsed); |
The code will output the following to the Scripts Background Screen:
*** Script: Shoe Size: 13
*** Script: Hat Size: 7.25
*** Script: Log Object
Object
shoe: Object
model: string = Air Jordan
make: string = Nike
size: string = 13
hat: Object
condition: string = new
type: string = cap
size: string = 7.25
Just what I needed. Thanks!
How would you do this if you don’t know the payload structure? Thinking if the keys are unknown.