FujiForty - JSON Processor API Shortcut

After the initial frustration with a locked down and undocumented Fuji scripted processor API I avoided them as much as possible. But sometime you just can't avoid them. I recently had a need to build a REST-like integration because the client app couldn't use SOAP, so scripted web services weren't an option. Since scripted REST services don't exist...yet, I needed to use a scripted processor to capture a POST request with JSON and return a JSON payload. 

Here's how I would have accomplished it pre-Fuji.

//build an object to work with
var responseObj = {};
//set some properties
responseObj.company = "CAVUCode";
responseObj.employees= [{"first":"john","last":"roberts"}];

//need to convert the object to a string
var responseStr = new global.JSON().encode(responseObj);

//write the string and specify content-type header
g_processor.writeOutput("application/json", responseStr);

This works just fine. It sets the content type so the client can interpret the response string as JSON.

{
  "company": "CAVUCode",
  "employees": [
    {
      "first": "john",
      "last": "roberts"
    }
  ]
}

 

While it's not a huge shortcut I did discover (now that it's documented) a new processor API method that makes this even easier.

For Fuji scoped applications you can simply pass an object to the writeJSON method. This accept an object parameter so no need to convert the object to a string or specify the content-type header.

//build an object to work with
var responseObj = {};
//set some properties
responseObj.company = "CAVUCode";
responseObj.employees= [{"first":"john","last":"roberts"}];

//send the json response
g_processor.writeJSON(responseObj); //not available in global

Disclaimer: I'm not sure why ServiceNow continues to publish new useful methods to only scoped apps, but this is another case. The writeJSON method is not available to global processors. Ugh!