18

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.

3
  • 2
    I don't see you set anything to display. But since there is console.log, you can open the developer console to see the result. Commented Jun 7, 2012 at 16:46
  • JSON is supposed to contain a single object, not two. Use JSONlint to validate it. Commented Jun 7, 2012 at 16:47
  • maybe opening the console? Press F12 Commented Jun 7, 2012 at 16:47

3 Answers 3

21

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);
})
Sign up to request clarification or add additional context in comments.

Comments

3
{"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.

Comments

0
{
    "items":[
        {
            "fname":"Asfahan",
            "lname":"Ahmad",
            "age":"25",
            "address":"bangalore"
        },
        {
            "fname":"Mohd",
            "lname":"Rehan",
            "age":"19",
            "address":"Tanda"
        }
    ]
}

save this json file with the name JSONData.json

` $.getJSON('JSONData.json',function(data){
                 $.each(data.items,function(key,value){
                     alert(value.fname);
                     alert(value.lname);
                     alert(value.age);
                     alert(value.address);
                 })`enter code here`
             })`

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.