Home > Net >  Iterate through JSON File in Javascript
Iterate through JSON File in Javascript

Time:01-28

I want to work with an JSON File in Javascript I got from my Flask server via a Axios Get-Request.

Its build like this:

{
  "data": [
    {
      "item": "[224,4,1,80,207,137,153,132]", 
      "name": "A1"
    }, 
    {
      "item": "[224,4,1,80,207,137,153,136]", 
      "name": "A2"
    }, 
    {
      "item": "[224,4,1,80,207,137,157,190]", 
      "name": "A3"
    }
  ]
}

I make my request with this and I can see the output in the terminal:

getInitialBoxesA() {
      const path = 'http://localhost:5000/getAllBoxesA';
      axios.get(path)
        .then((res) => {
          console.log(res.data);
        })
        .catch((error) => {
          // eslint-disable-next-line
          console.error(error);
        });
    },

How can i iterate through this Array in Javascript?

I tried res.data[0] or res.data[0].item

CodePudding user response:

Axios returns the actual response body in res.data. Given your JSON, you would need to iterate on res.data.data.

CodePudding user response:

try this

iterate(res.data.data);

function iterate(obj) {
  Object.keys(obj).forEach((key) => {
      if (typeof obj[key] === "object") {
      iterate(obj[key]);
    } else   console.log(`key: ${key}, value: ${obj[key]}`);
  });
};

output

key: item, value: [224,4,1,80,207,137,153,132]
key: name, value: A1
key: item, value: [224,4,1,80,207,137,153,136]
key: name, value: A2
key: item, value: [224,4,1,80,207,137,157,190]
key: name, value: A3
  •  Tags:  
  • Related