How To Read JSON Using JQuery

You might already know how to read a JSON file using PHP, but the truth is that it’s always better to avoid server connections, and for this, JQuery has a neat function that allows us to read external and local JSON files.

jQuery.getJSON( url, [data], [callback] )

The first parameter of this function, the URL you are planning to read, is required. The second parameter is used if you need to POST data to the URL. Last but no least, the callback function, although not required, is almost always necessary.

Important: The URL can be to a local or external file. If the file is in another server the URL must contain a callback variable. You’ll see how this works in the next paragraphs.

The Json File

Rather than making my own JSON file, like I’ve done for previous XML and JSON tutorials, I’ve decided that we’ll use Twitter’s search API this time.

Twitter’s search API has many different search options, but you only need to know about the callback and query “q” options.

Most basic Twitter search URL.

http://search.twitter.com/search.json?callback=foo&q=google+wave

Although required in the URL, your script does not have to have a callback function or variable. Just give the callback a value of “?” like this.

http://search.twitter.com/search.json?callback=?&q=google+wave

Important: Different APIs have different callback URL names, flickr’s API for example uses "jsoncallback" instead of "callback" in the URL. Always read the API docs very carefully.

Now that you know what it takes to query Twitter, take a look a sample response.

{"results":[
     {"text":"@twitterapi  http:\/\/tinyurl.com\/ctrefg",
     "to_user_id":396524,
     "to_user":"TwitterAPI",
     "from_user":"jkoum",
     "id":1478555574,   
     "from_user_id":1833773,
     "iso_language_code":"nl",
     "source":"<a href="http:\/\/twitter.com\/">twitter<\/a>",
     "profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/118412707\/2522215727_a5f07da155_b_normal.jpg",
     "created_at":"Wed, 08 Apr 2009 19:22:10 +0000"}],
     "since_id":0,
     "max_id":1480307926,
     "refresh_url":"?since_id=1480307926&q=%40twitterapi",
     "results_per_page":15,
     "next_page":"?page=2&max_id=1480307926&q=%40twitterapi",
     "completed_in":0.031704,
     "page":1,
     "query":"%40twitterapi"}]
}

This response only returned one result but you need not worry about that.

In this API the set of results begin with “[” and end with “]”. Every time you see this symbols it means that you loop through the set in them.

Retrieving The Results

Let’s begin building our JSON reading script. This script will be a twitter search script, so we are going to need a text box, a button and a div where we show the results.

<input type="text" id="query" /><button>Search</button>
<div id="results"></div>

The JQuery part will have the following structure

$(document).ready(function(){
    // twitter api's base url
    var url="http://search.twitter.com/search.json?callback=?&q=";
    // we'll store the search term here
    var query;
    
    // when the user clicks the button
    $("button").click(function(){
          // get value in the search box and store it in the variable
          query=$("#query").val();
          // get the json file
    });
});

Okay, we have the basic set up, it’s now time to build the getJSON part.

Our URL parameter will be the URL concatenated with the query (url+query). Since we are not posting data we don’t need the second parameter. The function getJSON returns a JSON object which we will use as parameter for the callback function.

// get the json file
 $.getJSON(url+query,function(json){
    // this is where we can loop through the results in the json object
});

Looping Through The Results

Notice that we passed an object called “json” to the callback function, you can change the name of this object but I think json makes sense. This object now contains all the json data we need, all we need to to now is loop through the results sent from twitter.

// this is where we can loop through the results in the json object
$.each(json.results, function(i,tweet){
     // this is where we do what we want with the tweet
});

Let’s break down the loop. the first parameter “json.results” refers to the array in the object we want to loop through, since the only array in the json response from the Twitter search API is “results” we say json.results. The second parameter, the function, has two parameters and you can change the name of them if you want to, I used "i" and "tweet".

The the “i” refers to the current number of loops and you could use if for example to display the number of results you got from the query. The “tweet” refers to the current tweet, so you can refer to any of the following keys by prepending the word “tweet” before them.

{
"text":"@twitterapi  http:\/\/tinyurl.com\/ctrefg",
     "to_user_id":396524,
     "to_user":"TwitterAPI",
     "from_user":"jkoum",
     "id":1478555574,   
     "from_user_id":1833773,
     "iso_language_code":"nl",
     "source":"<a href="http:\/\/twitter.com\/">twitter<\/a>",
     "profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/118412707\/2522215727_a5f07da155_b_normal.jpg",
     "created_at":"Wed, 08 Apr 2009 19:22:10 +0000"
}

To get the username from which the tweet originated you would use tweet.from_user , to get the actual tweet you would use tweet.text.

Let’s put the profile image and tweet in our div tag.

// this is where we can loop through the results in the json object
$.each(json.results,function(i,tweet){
     // this is where we do what we want with each tweet
    $("#results").append('<p><img src="'+tweet.profile_image_url+'" widt="48" height="48" />'+tweet.text+'</p>');
});

The full script

<input type="text" id="query" /><button>search</button><br />
<div id="results">

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var url='http://search.twitter.com/search.json?callback=?&q=';
var query;
	$('button').click(function(){
		query=$("#query").val();
		$.getJSON(url+query,function(json){
			$.each(json.results,function(i,tweet){
			   $("#results").append('<p><img src="'+tweet.profile_image_url+'" widt="48" height="48" />'+tweet.text+'</p>');
			});
		});		
	});
});
</script>

More JSON API’s

Here’s a list of some API’s that return JSON for you to pratice. Let me know if you of more.
Flickr
bit.ly
Best Buy