1

I am new in javascript. I am having problem with simple json file reading. Here is the sample code.

   function readJson() {
        $.getJSON('./resources/json/comments_type.json', function(data) {
            $.each(data, function(index, comment) {
                tempList.push(comment);
            });
        });



        for(var i = 0 ; i<tempList.length;i++)
        {
            console.log(tempList[i].text);
        }

    }

Here I was trying to iterate the tempList array after reading from the JSON file. But the console.log is not showing anything. But if I try console.log(tempList) it works. tempListis a global variable. I am calling the readJson function from another function. The JSON file saved here JSON file

Samiul Alam Anik
  • 111
  • 3
  • 14

2 Answers2

1

You seem to be running the for loop before you actually get any data as $.getJSON is asyncronous. So try moving the iterator loop to the $.getJSON callback.

function readJson() {
    $.getJSON('./resources/json/comments_type.json', function(data) {
        $.each(data, function(index, comment) {
            tempList.push(comment);
        });

        //Here you should have the list
        for(var i = 0 ; i<tempList.length;i++)
        {
            console.log(tempList[i].text);
        }
    });
}
DeadAlready
  • 2,988
  • 19
  • 18
0

readJSON function is called asynchronously. It means it is loading JSON from url (in another thread) when you already started to console.log content of tempList. Make sure that you read temp list after downloading it. It is usually done by callback. Or you could make this request synchronous (but it is wrong approach).

function readJson() {
    $.getJSON('./resources/json/comments_type.json', function(data) {
        $.each(data, function(index, comment) {
            tempList.push(comment);
        });
       for(var i = 0 ; i<tempList.length;i++)
       {
          console.log(tempList[i].text);
       }
    });     
 }

Try this way. You should get printed list. You could also pass callback to readJson function:

    function readJson(callback) {
    $.getJSON('./resources/json/comments_type.json', function(data) {
        $.each(data, function(index, comment) {
            tempList.push(comment);
        });
       callback();
    });     
 }

And then somewhere else in the code:

readJson(function(){
    for(var i = 0 ; i<tempList.length;i++)
       {
          console.log(tempList[i].text);
       }
});
Dawid C
  • 413
  • 3
  • 10