Parsing Twitter Json text using Javascript

2020-07-27 19:01发布

I need help with parsing of JSON feed text returned from Twitter. I need to access, and apply style tags to the link, created_date, and other info. Any hints on how to accomplish this? Thanks in advance

5条回答
再贱就再见
2楼-- · 2020-07-27 19:35

It'd be much easier to parse on the server-side, but I'm guessing you are doing the site entirely client-side?

sample Javascript:

    //store your JSON into a variable  
    var yourJSON = {"animals": 
                       [ {"type": "dog",  "name": "Paul"},
                         {"type": "cat",  "name": "Ralph"},
                         {"type": "bird", "name": "Jim"} ]
                   };

    //retrieve data and store into variables (do with them what you will)
    var PaulsType = yourJSON.animals[0].type; //returns 'dog'
    var BirdsName = yourJSON.animals[2].name; //returns 'Jim'


So with Twitter, there are a many levels of encapsulation, so you need to adjust accordingly. For example, for getting your followers, you'll have something like this:

[{"statuses_count":527,"profile_use_background_image":true, ....
....
,"status":{"place":null,"retweeted_status": {"place":null,"coordinates":null,"retweet_count":"100+","truncated":false,"text":"BLAHBLAHBLAH" .....

So this is just showing index 0. If you wanted to return the text of your first follower's most recent tweet (person who most recently followed you), you'd have to use javascript like this. In this example, the tweet is a retweet (to show use of encapsulation):

var yourJSON = {put Twitter output here};
var firstFollowersTweet_retweet = yourJSON[0].status.retweeted_status.text;

//to get raw text whether retweet or not
var firstFollowersTweet = yourJSON[0].status.text;


POW

查看更多
太酷不给撩
3楼-- · 2020-07-27 19:51

First results on google:

Ralph Whitbeck - Blog - Pulling twitter updates with JSON and jQuery. Code below:

var url = "http://twitter.com/status/user_timeline/RedWolves.json?count=3&callback=?";
$.getJSON(url, function(data){
    $.each(data, function(i, item) {
        $("img#profile").attr("src", item.user["profile_image_url"]); 
        $("#tweets ul").append("<li>" 
                                + item.text.linkify() 
                                + " <span class='created_at'>" 
                                + relative_time(item.created_at) 
                                + " via " 
                                + item.source
                                + "</span></li>");
    });
});

And the html:

<div id="tweets">
    <img id="profile">
    <ul></ul>
</div>

Another example. Fetching tweets with jQuery and the Twitter JSON API. Reproducing below:

$(document).ready(function() {
  // Declare variables to hold twitter API url and user name
  var twitter_api_url = 'http://search.twitter.com/search.json';
  var twitter_user    = 'lupomontero';

  // Enable caching
  $.ajaxSetup({ cache: true });

  // Send JSON request
  // The returned JSON object will have a property called "results" where we find
  // a list of the tweets matching our request query
  $.getJSON(
    twitter_api_url + '?callback=?&rpp=5&q=from:' + twitter_user,
    function(data) {
      $.each(data.results, function(i, tweet) {
        // Uncomment line below to show tweet data in Fire Bug console
        // Very helpful to find out what is available in the tweet objects
        //console.log(tweet);

        // Before we continue we check that we got data
        if(tweet.text !== undefined) {
          // Calculate how many hours ago was the tweet posted
          var date_tweet = new Date(tweet.created_at);
          var date_now   = new Date();
          var date_diff  = date_now - date_tweet;
          var hours      = Math.round(date_diff/(1000*60*60));

          // Build the html string for the current tweet
          var tweet_html = '<div class="tweet_text">';
          tweet_html    += '<a href="http://www.twitter.com/';
          tweet_html    += twitter_user + '/status/' + tweet.id + '">';
          tweet_html    += tweet.text + '<\/a><\/div>';
          tweet_html    += '<div class="tweet_hours">' + hours;
          tweet_html    += ' hours ago<\/div>';

          // Append html string to tweet_container div
          $('#tweet_container').append(tweet_html);
        }
      });
    }
  );
});
查看更多
来,给爷笑一个
4楼-- · 2020-07-27 19:51

There's a good reason to access the Twitter API from the client-side instead of the server side. If you are accessing their API on the server side with PHP, the server's IP may be rate-limited by Twitter. Furthermore, it seems that Twitter may not have published rate limits.

Using the REST API won't help, as the limit is too low to develop a site for a unknown count (potentially large number) of users. This is not scalable.

Using JavaScript it may be easier to have the client request the data instead.

It would be possible to OAuth each client and using his/her own API-Limit, but what a headache just for getting some tweets. I think, the generic using is an easier bypassing way.

查看更多
smile是对你的礼貌
5楼-- · 2020-07-27 19:53

If you want to convert JSON to HTML, there is a nice template engine: tempo js

查看更多
够拽才男人
6楼-- · 2020-07-27 19:56

Look at $.json, it is made specifically for this. It is an ajax call, that automatically parses the json on return (into an array) to be used in the callback.

查看更多
登录 后发表回答