Home > front end >  traversing json object structure contains arrays
traversing json object structure contains arrays

Time:03-16

So i have the following structure.. How can iterate over "values" structure to extract all the possible "paramX" arrays... can i use a loop?

Im getting this structure from a call to external service from a javascript call.. So in java script.

{

  "booleanValue": true,

  "values": {

    "param1": ["1.00", "20.00"],

    "param2": [ "2,000.00", "200.00"],

    "param3": [  [  "Test1",  "CC1", ], [  "T222222",  "CC2212", ]    ]

  }

}

CodePudding user response:

Here I use Object.keys() to return an array of keys in values and then do a forEach loop on that array:

var str = `{
  "booleanValue": true,
  "values": {
    "param1": ["1.00", "20.00"],
    "param2": ["2,000.00", "200.00"],
    "param3": [["Test1",  "CC1"],["T222222","CC2212"]]
  }
}`;

var obj = JSON.parse(str);

Object.keys(obj.values).forEach(key => {
  console.log(key, obj.values[key]);
});

CodePudding user response:

I am just tossing this in to be helpful .. You can see how JSON.parse works with JavaScript.

No need to "loop" with the example you gave .. But you definately could if you wanted to ..

let json = `{
  "booleanValue": true,
  "values": {
    "param1": ["1.00", "20.00"],
    "param2": [ "2,000.00", "200.00"],
    "param3": [  [  "Test1",  "CC1" ], [  "T222222",  "CC2212" ]    ]
  }
}`

const obj = JSON.parse(json);

console.log(obj.booleanValue);

console.log(obj.values.param1[0]);

console.log(obj.values.param3[0][0]);

  • Related