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

2
  • You're doing .length on an object. Commented Jul 7, 2021 at 15:11
  • The json.data.item is not an array. you need to run a for loop like jsfiddle.net/Lf7honqy Commented Jul 7, 2021 at 15:15

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.