Uffo
Uffo

Reputation: 10046

How to parse json response from twitter

So I'm doing a request like this: https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=3

Now, I'm using jQuery, and I'm trying to display the data like this:

  success: function(data, textStatus, xhr) {

    if(data)
    {
    for (var i = 0; i < data.length; i++) {
      $("#at .tweet-message").html(data.text);
    };

I want to display 3 tweets, what I'm doing wrong?

Upvotes: 1

Views: 1011

Answers (2)

soulcheck
soulcheck

Reputation: 36767

You're missing the index when referencing data array elements (apart from some braces):

success: function(data, textStatus, xhr) {

    if(data) {
        for (var i = 0; i < data.length; i++) {
           $("#at .tweet-message").html(data[i].text); //here
        }
    }
}

edit

It shows only one tweet because you're using html() instead of, for example, append(). You substitute the element content in each iteration.

Upvotes: 5

Andreas Louv
Andreas Louv

Reputation: 47099

Another way by chaching data.length. Just extented soulcheck's answer

success: function(data, textStatus, xhr) {
    var i = 0,
        len = data ? data.length : 0;

    for ( ; i < len; i++ ) {
        $("#at .tweet-message").html(data[i].text);
    }
}

len = data ? data.length : 0 means:

if ( data ) {
    len = data.length;
}
else {
    len = 0;
}

Upvotes: 1

Related Questions