I have a request JSON payload, which contains number, string, Boolean and array values.
{ "name": "vivek", "age": "12", "employed": true, "cars": ["maruti", "wagonR"] }
When i extract these values in JavaScript, they are extracted without quotes.Similar is the case with Extract variable policy.
But i want to detect the case, where age comes with quotes i.e.{"age":"12"} and throw some error.
The only acceptable case should be {"age":12} for age.
What are the possible ways to validate this?
Solved! Go to Solution.
I would do it in one of two ways:
1. a simple approach, using a JavaScript callout.
2. a general approach, using a Json schema.
If you choose to use a simple JS callout, you could use code like this:
var body = JSON.parse(request.content); if (body.hasOwnProperty('age')) { if (typeof body.age === 'string') { // can take one of 2 actions here. Throw an exception. // or convert the value. // // option 1: throw an exception. // Handle this in FaultRules. throw new Error('illegal format'); // option 2: convert the string to a number body.age = parseInt(body.age, 10); // re-serialize the request context.setVariable('request.content', JSON.stringify(body, null, 2)); } }
Embed the above code into a script, and then configure it with a JavaScript callout policy.
JSON schema is a more general way of specifying the required structure of a payload. For example, instead of just one field "age" that you wish to validate, suppose you have a large set of fields you want to validate for type and presence. JSON Schema allows you to be very explicit about all of that.
What you'd need to do is create a schema stipulating the required structure of the message, then use a Java callout or JS callout to verify the JSON received against the schema you have.
I have an example in Java that does this, here.