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

How to remove few fields from JSON array response?

I am getting a JSON response like below:

[
  {
    "id": "1",
    "name": "Abhi",
    "pan": "ABC",
    "bg": "O+"
  },
  {
    "id": "2",
    "name": "Ashish",
    "pan": "XYZ",
    "bg": "AB+"
  },
  .
  .
  .
]
and I want to remove the "pan" and "bg" field from all elements of the array in the final response.Like below:
[
  {
    "id": "1",
    "name": "Abhi"
  },
  {
    "id": "2",
    "name": "Ashish"
  },
  .
  .
  .
]
Solved Solved
1 10 21.3K
1 ACCEPTED SOLUTION

I have resolved this issue placing a Javascript Policy between Extract variable policy and Assign Message policy.

Inside Javascript policy, I'm taking the whole payload in a variable, converting it to an array, mapping required fields to another array, and then converting the second array to JSON object.

Extract Variable Policy code:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ExtractVariables async="false" continueOnError="false" enabled="true" name="EV-FullData">
    <DisplayName>EV-FullData</DisplayName>
    <Properties/>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <JSONPayload>
        <Variable name="resp">
            <JSONPath>$</JSONPath>
        </Variable>
    </JSONPayload>
    <Source clearPayload="false">response</Source>
    <VariablePrefix>apigee</VariablePrefix>
</ExtractVariables>

Javascript Policy code:

var res = context.getVariable("apigee.resp");
var result = [];
var result = JSON.parse(res);
var newArr = result.map(item => { return {
  id: item.id,
  name: item.name
}});
var output = JSON.stringify(newArr);
context.setVariable("apigee.resp",output);

Assign Message Policy code:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="AM-FinalResponse">
    <DisplayName>AM-FinalResponse</DisplayName>
    <Properties/>
    <Set>
        <Payload>
            {apigee.resp}
        </Payload>
    </Set>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="response"/>
</AssignMessage>

View solution in original post

10 REPLIES 10