how to write a javascript to get nested JSON array objects like below?

"A": { "B": [ { "B": [ { "B": [ { "B":[] } ] } ] } ] }

0 4 27.5K
4 REPLIES 4

@Sakthivel , How is this related to Apigee Developer Portal / Apigee Edge ? If it's general programming question please post same in stackoverflow. If it's Apigee related, please explain what you are trying to do with more details.

Hi,

my requirement is, when JSON returns the nested array structure like below, i need to write a java script code to extract each "subaddresscomponents"

"subAddress": { "subAddressComponents": [ { "id": "263317533", "subAddressComponents": [ { "id": "263317550", "subAddressComponents": [ { "id": "418703244", } ] } ] } ] }

Hi @Sakthivel Working with JSON objects within a JavaScript policy in Apigee Edge is identical to how you handle it in a regular JavaScript program.

A code snippet like below will go into your JavaScript policy.

var dictionary = {"data":[{"id":"0","name":"ABC"},{"id":"1", "name":"DEF"}], "images": [{"id":"0","name":"PQR"},{"id":"1","name":"xyz"}]};
for (item in dictionary) {
  for (subItem in dictionary[item]) {
     console.log(dictionary[item][subItem]);
  }
}

Checkout this help page here

HI @Sakthivel

You can extract the values using Extract Variables.

<ExtractVariables name="ExtractVariables-3">
   <Source>response</Source>
   <JSONPayload>
      <Variable name="id" type="nodeset">
         <JSONPath>$.subAddress..subAddressComponents[0].id</JSONPath>
      </Variable>
   </JSONPayload>
   <VariablePrefix>subAddressVarPrefix</VariablePrefix>
</ExtractVariables>

This will give you an array of ids --> ["263317533", "263317550", "418703244"]

Similarly you can extract others as well.

Tip: I normally use jsonpath.com to test my json path conditions and then use them in my policy

Hope this helps.