Alexis P
Alexis P

Reputation: 549

Read JSON Array with jQuery

I am trying to output some JSON objects in the console but it doesn't seem to work. This JSON comes from a mini API that I have created using PHP.

My JSON looks like this:

{
    TotalResults: 2,
    Results: [
        {
            UserName: "Sarah",
            ModifDate: "2014-12-01T08:03:40.000+00:00",
            ID: "54321",
            Title: "Brilliant",
            RText: "This is a brilliant product"
        },
        {
            UserName: "Joe",
            LastModificationTime: "2014-11-01T08:03:40.000+00:00",
            Id: "12345",
            Title: "Excellent",
            RText: "This is a great console,"
        }
    ]
}

My Javascript:

$.ajax({
    url:'http://myapi.com?api=1&test=test',
    dataType: 'json',
    type: 'get',
    cache: false,
    success:function(data){
        for (var i in data) {
        var count = data[i].TotalResults;
        var name = data[i].Results.UserName;
        var text = data[i].Results.RText;
        console.log(name);
        console.log(text);
        }
    }
}); 

However, nothing is being returned and I get the following in the console log:

Uncaught TypeError: Cannot read property 'TotalResults' of undefined

Do you guys have an easier way to read JSON data in an array?

I eventually want to output this data in the DOM as HTML.

Upvotes: 1

Views: 123

Answers (2)

Sn0opr
Sn0opr

Reputation: 1026

The way you are reading the JSON response is wrong

You should read the data object like a normal/native Javascript/JSON object:

In your success callback function:

function(data) {
//data.Results is the array , we fetch it using the forEach Javascript function, you can use for also...
data.Results.forEach(function(result) {
    console.log(result.UserName)
    ...
})}

You don't even need to send the TotalResult property because you can get the array length like a native Javascript array: data.Results.length.

So in other world you whene you are reading a JSON data, read it like a simple Javascript object.

Upvotes: 0

ntzm
ntzm

Reputation: 4821

$.ajax({
    url:'http://myapi.com?api=1&test=test',
    dataType: 'json',
    type: 'get',
    cache: false,
    success:function(data){
        for (var i in data.Results) {
        var count = data.TotalResults;
        var name = data.Results[i].UserName;
        var text = data.Results[i].RText;
        console.log(name);
        console.log(text);
        }
    }
});

Your iteration was a bit dodgy, this should work now.

Here is a JSFiddle to show it works: http://jsfiddle.net/n7afxhed/

Upvotes: 3

Related Questions