Create a contact table from JSON data

I recently started a demo project on HTML, JSON and jQuery. Now I want to get data from a JSON file and load it into a table. I am new to JSON, so it took me a day to do nothing, the data was not loaded into my table.

Here is my JSON file, 'contact.json':

{
    "length": 2,
    "info": [
        {
            "fullname":"Noob Here",
            "email":"myemail@server.com",
            "phone":"123456",
            "badgeid": "11111",
        },
        {
            "fullname":"Newbie There",
            "email":"hisemail@server.com",
            "phone":"589433",
            "badgeid": "11112",
        }
    ]
}

My script to load data:

window.onload = function () {
    var contacts;
    setTimeout(loadData(contacts, "contact"), 2000);
    $(contacts.info).each(function(index, element){  
        $('#contacts').append('<tr><td>' + element.fullname + '</td><td>'
            + element.email + '</td><td>'
            + element.phone + '</td><td>'
            + element.badgeid + '</td></tr>');       
    })
};

function loadData(myobject, myfile){
    myobject = $.parseJSON("../data/" + myfile + ".json");
};

Please note that I can boot from different JSON files, so loadData has some features. Otherwise, it will parse the JSON file directly.

I already had the table "#contact" declared in HTML. The error console states:

Untrained SyntaxError: Unexpected token.
    jQuery.extend.parseJSONjquery.min.js: 442
    loadDataHomepage.html: 23
    window.onload

? ?

+2
2

JSON JSON, JSONLint.com. JSON:

{
    "length": 2,
    "info": [
        {
            "fullname":"Noob Here",
            "email":"myemail@server.com",
            "phone":"123456",
            "badgeid": "11111",  <---- Do not put a comma before a curly brace
        },
        {
            "fullname":"Newbie There",
            "email":"hisemail@server.com",
            "phone":"589433",
            "badgeid": "11112",  <---- remove comma before curly brace
        }
    ]
}

JSON :

{
    "length": 2,
    "info": [
        {
            "fullname":"Noob Here",
            "email":"myemail@server.com",
            "phone":"123456",
            "badgeid": "11111"
        },
        {
            "fullname":"Newbie There",
            "email":"hisemail@server.com",
            "phone":"589433",
            "badgeid": "11112"
        }
    ]
}
+1

JSON.parse

, JSON

script :

    window.onload = function () {
       var contacts;
       $.getJSON('contact.json',function(contacts)
        {
          $(contacts.info).each(function(index, element){  
               $('#contacts').append('<tr><td>' + element.fullname + '</td><td>'
                 + element.email + '</td><td>'
                 + element.phone + '</td><td>'
                 + element.badgeid + '</td></tr>');       
           })  
        });
     };
+3

All Articles