Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read JSON File with jQuery

Tags:

json

jquery

Hey I'm trying to read data from a JSON File with jQuery. This is my JS:

$(document).ready(function() {
    var myItems;

    $.getJSON('testData.json', function(data) {
        myItems = data.items;
        console.log(myItems);
    });
});

And that is the JSON File:

{"fname":"rafael","lname":"marques","age":"19"}
{"fname":"daniel","lname":"marques","age":"19"}

When I open my HTML Page in the Browser I can't see nothing in the Console.

like image 233
Rafael Marques Avatar asked Jun 07 '12 16:06

Rafael Marques


1 Answers

Add comma after each object, wrap then with [] and enclosed them with an object with property items in json file so it will look like

{
    items: [
    {
        "fname": "rafael",
        "lname": "marques",
        "age": "19"},
    {
        "fname": "daniel",
        "lname": "marques",
        "age": "19"
    }]
}

then you should try for

$.each(data.items, function(key, val) {
   alert(val.fname);
   alert(val.lname);
})
like image 78
thecodeparadox Avatar answered Oct 21 '22 06:10

thecodeparadox