jQuery: Twitter JSON feed

In this post I'm going to show you how to retrieve the contents of a Twitter JSON feed, parse and format it with jQuery. We first need to know what's our current feed URL. Generally, Twitter places our status feed at this URL:


username is our Twitter username, while count is the number of tweets we want to retrieve. Before writing our jQuery code, we have to address the problems of Twitter URLs. Such URLs are not wrapped with HTML links but they're returned as raw text. So we need to write a simple jQuery global utility function that converts these URLs into HTML links:

(function($) {
    $.toLink = function(text) {
        var urlRegExp = /((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/gm;
        var newText = text.replace(urlRegExp, '<a href="$1">$1</a>');
        return newText;

toLink() converts an URL into an HTML link by comparing it against a regular expression and then by replacing it with the JavaScript replace() method.

Now we can use $.getJSON() to retrieve and parse our JSON feed:

$(function() {

var twitterBaseURL = 'http://twitter.com/status/user_timeline/username.json?count=5&callback=?';
var html = '';

$('<ul />').appendTo('#twitter');

$.getJSON(twitterBaseURL, function(json) {

   $.each(json, function(i, item) {
     var text = $.toLink(item.text);
     var profileImageURL = item.user.profile_image_url;
     html += '<li><img src="' + profileImageURL + '" />' + text + '</li>';
   $('ul', '#twitter').html(html);


As you can see, we get the text property of each object in the JSON array and the URL of our profile image stored in the profile_image_url property of the user object. I recommend you to study the source of the JSON file opening the following URL in your browser:


where username is your Twitter username and n is the number of tweets you want to retrieve. You can see the demo below.


Live demo

One thought on “jQuery: Twitter JSON feed”

Leave a Reply

Note: Only a member of this blog may post a comment.