Validate Message JSON

Hi

I want to validate a json that is passed as a form param. I used an extract variable policy to create

a variable with the value of form param. And then try using a Validate Message policy to validate that content is JSON. Following through the link below.

https://www.youtube.com/watch?v=iO2CW6ymN7U

In the video the source is request, however i am providing the value of the variable that i populated in the extract variable policy. I am getting an exception. Moreover, it seems to validate based on content type specified in the request.

Can we use validate message independently too esp if one of the param is json but the form request is x/formurl-encoded.

thanks aakash

Solved Solved
0 1 455
1 ACCEPTED SOLUTION

According to documentation ,

"If a <ResourceURL> value is not specified, the message is checked for well-formed JSON or XML if the content-type is application/json or application/xml, respectively."

So , i guess this policy can't be used with variable.

You can use something like below to check validity of JSON in javascript

var formparamjson = context.getVariable("formparam_jsonstring");

try {
    formparamjson = JSON.parse("formparamjson");
} catch (ex) {
    context.setVariable("isValidJson", false);
    context.setVariable("errorMessage", ex.message);
}
<br>

You can have a conditional step to raise fault based on isValidJson variable and can send proper error message to consumers.

Hope this will help.

View solution in original post

1 REPLY 1

According to documentation ,

"If a <ResourceURL> value is not specified, the message is checked for well-formed JSON or XML if the content-type is application/json or application/xml, respectively."

So , i guess this policy can't be used with variable.

You can use something like below to check validity of JSON in javascript

var formparamjson = context.getVariable("formparam_jsonstring");

try {
    formparamjson = JSON.parse("formparamjson");
} catch (ex) {
    context.setVariable("isValidJson", false);
    context.setVariable("errorMessage", ex.message);
}
<br>

You can have a conditional step to raise fault based on isValidJson variable and can send proper error message to consumers.

Hope this will help.