syntax_macros icon indicating copy to clipboard operation
syntax_macros copied to clipboard

JSON_Response_Builder.js

Open ashoo-jindal opened this issue 1 year ago • 0 comments

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): true or false, 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:

  1. API Responses: Return structured responses from ServiceNow APIs.
  2. Script Logging: Log the success, message, and additional data in a standardized format.
  3. Client-Side Communication: Send consistent JSON responses back to client scripts or UI actions.

ashoo-jindal avatar Oct 07 '24 10:10 ashoo-jindal