如何打印JSON数据?

I try to get a JSON file on my local host but on console I receive an array with my all objects from data.json but I receive the following error

Uncaught TypeError: Cannot read property 'forEach' of undefined

This is my code:

$.ajax({
        type : 'GET',
        dataType : 'json',
        url: 'http://localhost:8888/data/folder/data.json',
        success : function(data) {
            console.log(data); 
        var data =[];
        var covers = document.getElementById("covers");
        var blockTemplate = covers.getElementsByTagName("div")[0].cloneNode(true);
        covers.getElementsByTagName("div")[0].remove();
        data.info.forEach( function(obj) {
            block = blockTemplate.cloneNode(true);
            block.getElementsByTagName("a")[0].setAttribute('href', obj.link);
            block.getElementsByTagName("img")[0].setAttribute('src', obj.cover);
            covers.appendChild(block);
        });
    }
    });

Any idea how can I solve this?

Remove

var data =[];

From success().

This is overriding the ajax response.

Change success : function(data) { with success : function(response) { response in success and your data array is ambiguous. This will create problem. In javascript variables overrides when you'll define again.

Take a look here

What is the scope of variables in JavaScript?

var data = data.info;
    data.forEach( function(obj) {
      block = blockTemplate.cloneNode(true);
      block.getElementsByTagName("a")[0].setAttribute('href', obj.link);
      block.getElementsByTagName("img")[0].setAttribute('src', obj.cover);
      covers.appendChild(block);
    });

</div>

In your case I think that "info" object of "data" is not defined or not received from server.

You can also loop your json object as shown below :

if(typeof(data.info) != "undefined")
    for(i in data.info)
         {
                var obj = data.info[i];
                block = blockTemplate.cloneNode(true);
                block.getElementsByTagName("a")[0].setAttribute('href', obj.link);
                block.getElementsByTagName("img")[0].setAttribute('src', obj.cover);
                covers.appendChild(block);
         }
}