Read JSON File with jQuery

64,832

Solution 1

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);
})

Solution 2

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

Isn't a correct json file. Add a comma between the lines or make it like this :

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

to comply with your apparent requirements.

But opening the console to look at errors would have solved this.

Share:
64,832
Rafael Marques
Author by

Rafael Marques

Updated on June 08, 2020

Comments

  • Rafael Marques
    Rafael Marques about 4 years

    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.