How to escape double quotes in a JSON?

Smith Johnson
Tera Guru

Hi community,

I have the following field where the user can insert any character. For example:

find_real_file.png

Then, behind the scenes once the form is submitted, a script include makes a REST API call.
However, the double quotes that the user inserted make the integration fail.

The request body looks like this:

find_real_file.png

Any ideas on how to solve this??

 

Thank you in advance,

Smith.

1 ACCEPTED SOLUTION

use to \\ to escape

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

11 REPLIES 11

Hi,

did you try sending complete request body using JSON.stringify()

1) form the json object having double quotes

2) then use JSON.stringify() to convert that object and then send

please share your complete script here

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

@Ankur Bawiskar Thank you for the response. Where exactly should I stringify?? 

1) Here is the HTTP method:
find_real_file.png

2) Within the script include, I take the "description" value that the user inserted.

scope.params={
 "requestId": String(scope.targetRecord.number),
 "description": String(variables.vs_description),
 "region": String(variables.vs_region)
}



3) Then I have the following GenerateWSMessage:

new GenerateWSMessage({
            source: "ServiceNow",
            target: "VCI",
            integrationType: "REST",
            integrationEndPoint: "AWS API",
            integrationEndPointMethod: scope.params["endpoint"],
            documentId: (scope.targetRecord).getUniqueValue(),
            documentTableName: "sc_req_item",
            setParamsFn: function(wsObject) {
                    wsObject.setStringParameterNoEscape("requestId", scope.params["requestId"]);
                    wsObject.setStringParameterNoEscape("description", scope.params["description"]);
                    wsObject.setStringParameterNoEscape("region", scope.params["region"]);
            },
            responseCallBackFn: function(responseStatus, responseCode) {
                scope.responseParsed = {
                    "code": responseCode,
                    "response": responseStatus
                };
            },
            maxRetries: 1,
            extraInfoInIncidentTitle: " - VCIHelperCreateAWS - " + (this.targetRecord).number,
            createIncidentOnFailure: createIncident,
            exceptionErrorCodes: exceptionErrorCodes
        }).executeRequest();


4) The executeRequest method looks like this:

executeRequest: function() {
		var setParamsConfig = {};
		var retries = this.config.maxRetries;
		var exceptionErrorCodes = this.config.exceptionErrorCodes;
		var createIncidentOnFailure = this.config.createIncidentOnFailure;
		var createIncidentAssignmentGroup = this.config.createIncidentAssignmentGroup;
		var transaction = this._constructTransactionObject();
		var successfulResponse = false;
		var transactionHelper = null;
		var response = "";
		// default values for optional fields
		if(typeof(retries) == "undefined")
			retries = 3;
		if(typeof(exceptionErrorCodes) == "undefined")
			exceptionErrorCodes = [];
		if(typeof(createIncidentOnFailure) == "undefined")
			createIncidentOnFailure = true;
		if(typeof(createIncidentAssignmentGroup) == "undefined")
			createIncidentAssignmentGroup = 'Workgroup - Internal Snow';
		
		// setting the document glide record for "setParamsConfig"
		if(this.config.documentTableName && this.config.documentId) {
			setParamsConfig.documentGR = new GlideRecord(this.config.documentTableName);
			setParamsConfig.documentGR.get(this.config.documentId);
		}
		
		for(var i = 0; i < retries && !successfulResponse; i++) {
			// request preparation & execution
			try{
				var request;
				if(this._isREST())
					request = new sn_ws.RESTMessageV2(this.config.integrationEndPoint, this.config.integrationEndPointMethod);
				else if(this._isSOAP())
					request = new sn_ws.SOAPMessageV2(this.config.integrationEndPoint, this.config.integrationEndPointMethod);
				
				var endpointToUpdate = gs.getProperty("GenerateWSMessage.Endpoint."+this.config.integrationEndPoint+"."+this.config.integrationEndPointMethod);
				
				if(JSUtil.notNil(endpointToUpdate)){
					
					endpointToUpdate = unescape(endpointToUpdate);
					request.setEndpoint(endpointToUpdate);
					
				}
				
				this.config.setParamsFn(request, setParamsConfig);
				
				// handling fake responses
				var fakeResponse = gs.getProperty("GenerateWSMessage.FakeResponse." + this.config.integrationEndPoint+"."+this.config.integrationEndPointMethod);
				if(JSUtil.notNil(fakeResponse)) {
					response = {};
					transaction.endPointUrl = "FAKE";
					transaction.headers = "FAKE";
					transaction.message = "FAKE";
					transaction.response = 	fakeResponse;
					transaction.responseHttpCode = 200;
				} else {
					response = request.execute();
					transaction.endPointUrl = request.getEndpoint();
					transaction.headers = JSON.stringify(request.getRequestHeaders());				
					transaction.message = request.getRequestBody();
					transaction.response = response.haveError() ? response.getErrorMessage() + " - " + response.getBody() : response.getBody();	
					transaction.responseHttpCode = response.getStatusCode();
				}
				
			} catch(ex) {
				var message = ex.getMessage() || ex;
				transaction.response = message;
				transaction.responseHttpCode = 0;
				gs.log("ERROR GenerateWSMessage "+ message);
			}
				
			// retries logic (whether to continue retrying or halt) and
			// logging the transaction object to integration transactions table
			var responseCodeIs2xx = transaction.responseHttpCode >= 200 && transaction.responseHttpCode < 300;
			var responseCodeIsException = exceptionErrorCodes.indexOf(transaction.responseHttpCode) != -1;
			if(responseCodeIs2xx || responseCodeIsException) {
				if(responseCodeIs2xx)
					transaction.stage = "Sent";
				else
					transaction.stage = "Fail";
				successfulResponse = true;
				transactionHelper = new TransactionsHelper(transaction);
				this.config.responseCallBackFn(transaction.response, transaction.responseHttpCode);
			} else {
				transaction.stage = (i == retries - 1 ? "Fail" : "Retrying");
				
							
				transaction.response = response.getBody();
				transactionHelper = new TransactionsHelper(transaction);
				transaction.retries++;
			}
			
		}
		
		// raise P1 incident if all the retries failed
		if(!successfulResponse && createIncidentOnFailure) {
			var incTitle = gs.getMessage('integration_transaction_failure', [transactionHelper.getNumber()]);
			if(this.config.extraInfoInIncidentTitle)
				incTitle += this.config.extraInfoInIncidentTitle;
				
			var incidentGR = new GlideRecord('incident');
			incidentGR.initialize();
			incidentGR.urgency = 1;
			incidentGR.impact = 1;
			incidentGR.assignment_group.setDisplayValue(createIncidentAssignmentGroup);
			incidentGR.short_description = incTitle;
			incidentGR.insert();
		}
		
		return successfulResponse;
		
	},
	

Hi,

Did you try to hard-code the request body and include double quotes and check

try to use escape / before double quotes

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Is this a correct approach??

var description=String(variables.vs_description).replace(/["]/g, "\"");
wsObject.setStringParameterNoEscape("description", description);

use to \\ to escape

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader