Limiting array size in a JSON request

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 ?

2 Likes

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.

1 Like

Just one note… the json you posted isn’t valid json. In JSON the property names need to be quoted, and arrays are in square brackets only. Eg

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

@Dino

I had implemented a similar solution to what you suggested. Thanks for confirming my solution.