1

I tried to get the data from the json file with javascript but it doesn't output the data here is my code:

fetch('https://raw.githubusercontent.com/trvodi/test/main/json1.json')
  .then((res) => res.json())
  .then((data) => {
var json = data;
var i;
    var iLength = json.data.item.length;
    for (i = 0; i < iLength; i++) {
        alert(json.data.item[i].FromMember);
    }

}).catch((err) => {
    console.log(err)
  })

please help me. thank you

trung
  • 11
  • 1

1 Answers1

1

If you'd add the following line:

console.log(json.data.item, json.data.item.length);

You'll see that json.data.item.length is undefined because json.data.item is an object.

I'd recommend using

for (let i in json.data.item) {
    let item = json.data.item[i];
    console.log(item.FromMember);
}

To loop over the objects as shown in this demo:

fetch('https://raw.githubusercontent.com/trvodi/test/main/json1.json')
  .then((res) => res.json())
  .then((data) => {
      for (let i in data.data.item) {
          let item = data.data.item[i];
          console.log(item.FromMember);
      }
  })
.catch((err) => {
  console.log(err)
})

For more info about why (and alternatives) I'd choose for (let i in json.data.item), please see the following question/answer:

How to loop through a plain JavaScript object with the objects as members?

0stone0
  • 34,288
  • 4
  • 39
  • 64