Search code examples
javascriptjquerygetjson

JavaScript JSON data issue - alert not showing in each loop


I am having issues with some javascript code.

I am not getting the data alerted after the each loop area.

Here's the whole code:

var widget = {

    url: 'the url here', //no used yet

    readjson: function() {

       alert(this.url);   

       var  thedata = [
         {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
         {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
         {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
        ];

        alert(thedata); //I get this

            $.getJSON(thedata, function(data) {
                $.each(data, function(index) {
                    alert(data[index].TEST1); //No alert here
                    alert(data[index].TEST2); //No alert here
                });
        });

    }

};

widget.readjson();

Solution

  • [with a URL call :] same code as below for JSON string, but wrap with the AJAX call :

    $.getJSON('http://exemple.com/data.json' , function(data) {
        $.each(data, function() {
          alert(this.TEST1);
          alert(this.TEST2);
        });
    });
    

    [with a JSON sting :]

    var widget = {
      readjson: function() {
        var stringJsonData = '[{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}]';
    
        alert(stringJsonData);
        data = $.parseJSON(stringJsonData);
    
        $.each(data, function() {
          alert(this.TEST1);
          alert(this.TEST2);
        });
      }
    };
    
    widget.readjson();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


    This is a JSON string that you can parse with $.parseJSON() :

       var  thedata = '[
         {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
         {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
         {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
        ]';
    

    The main issue is that you try to use an AJAX call ($.getJSON()) that take a URL string as 1st parameter, with a hand crafted json object thing...

    For now, your is just a JS array of object you can process like this :

    var widget = {
      read: function() {
        var thedata = [{"TEST1": 45,"TEST2": 23,"TEST3": "DATA1"},{"TEST1": 46,"TEST2": 24,"TEST3": "DATA2"},{"TEST1": 47,"TEST2": 25,"TEST3": "DATA3"}];
    
        alert(thedata); //I get this
        $.each(thedata, function(index) {
          alert(this.TEST1); //No alert here
          alert(this.TEST2); //No alert here
        });
      }
    };
    widget.read();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>