syntax_macros
syntax_macros copied to clipboard
JSON_Response_Builder.js
buildJsonResponse Utility Function
This utility function helps in constructing standardized JSON responses for any operation. It accepts three parameters:
- success (Boolean): Indicates whether the operation was successful or not.
- message (String): Provides a message related to the operation's outcome.
- data (Object): Contains additional data relevant to the operation, such as key-value pairs or complex objects.
Function Overview
function buildJsonResponse(success, message, data) {
return JSON.stringify({
success: success,
message: message,
data: data
});
}
Parameters:
- success (Boolean):
trueorfalse, indicating if the operation succeeded. - message (String): Descriptive message for the response.
- data (Object): Data to include in the response, such as JSON objects, arrays, or key-value pairs.
Example Usage:
The example below shows how to build a JSON response after an operation:
var json_data = {
"key1": "value1",
"key2": "value2"
};
var response = buildJsonResponse(true, 'Operation successful', json_data);
gs.info('Response: ' + response);
Output:
The response will be logged in the system, and the JSON structure will look like this:
{
"success": true,
"message": "Operation successful",
"data": {
"key1": "value1",
"key2": "value2"
}
}
Key Benefits:
- Consistency: Generates consistent JSON responses for operations.
- Simplicity: Reduces the need for manual JSON construction in scripts.
- Scalability: Easily adaptable for logging, API responses, and internal handling of success/error responses.
Practical Use Cases:
- API Responses: Return structured responses from ServiceNow APIs.
- Script Logging: Log the success, message, and additional data in a standardized format.
- Client-Side Communication: Send consistent JSON responses back to client scripts or UI actions.