Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Limiting array size in a JSON request

Not applicable

I am trying to limit the number of elements in an array, which itself is a part of JSOn request. For ex:

JSON Request ->

{
  name: "xyz",
  type: "abc",
  arrayList:[{"a", "b", c"}]
}

So suppose I want to limit number of elements in "arrayList" to 2. Then the above request should fail. Any suggestions on how to achieve that ?

Solved Solved
2 3 8,199
1 ACCEPTED SOLUTION

yes, one way to do that is to insert a Javascript policy that parses the inbound JSON, and checks the length of the array. If it exceeds your limit (2), then the Javascript policy can set a variable. In the next step in your flow, you can add a condition that checks the variable, and Raises a fault if the variable is true.

Ex

<Step>
  <Name>Javascript-CheckArrayLength</Name>
</Step>
<Step>
  <Condition>arrayList.length.violation = true</Condition>
  <Name>RaiseFault-1</Name>
</Step> 

In the Javascript, you would do something like this:

var c = context.getVariable('request.content');
var body = JSON.parse(c);
if (!body || !body.arrayList || body.arrayList.length > 2) {
  context.setVariable('arrayList.length.violation', true);
}

If you want to do more structured verification, I suggest that you examine the JSONSchema standard, and insert a Java or JS policy that checks the inbound message against the schema.

I think there have been previous questions here on this forum regarding JSON Schema.

View solution in original post

3 REPLIES 3
Top Solution Authors