Sunday, March 25, 2012

How To Read JSON Using JQuery

64 comments
This script to search data from twitter using a search box :
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>


64 comments:

  1. Very Interesting information shared than other blogs
    Thanks for Sharing and Keep updating us

    ReplyDelete
  2. Australia Best Tutor is one of the best Online Assignment Help providers at an affordable price. Here All Learners or Students are getting best quality assignment help with reference and styles formatting.

    Visit us for more Information

    Australia Best Tutor
    Sydney, NSW, Australia
    Call @ +61-730-407-305
    Live Chat @ https://www.australiabesttutor.com




    Our Services

    Online assignment help Australia
    my assignment help Australia
    assignment help
    help with assignment
    Online instant assignment help
    Online Assignment help Services

    ReplyDelete
  3. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    best wireless bluetooth headphones
    best power bank for mobile
    dual sim smartphone
    keypad mobiles with wifi and whatsapp
    best smartphone accessories

    ReplyDelete
  4. I have read your blog its very attractive and impressive. I like it your blog.
    bosch simultaneous interpretation system

    ReplyDelete
  5. Thanks for sharing this blog. This very important and informative blog Learned a lot of new things from your post! Good creation and HATS OFF to the creativity of your mind.
    Very interesting and useful blog!
    simultaneous interpretation equipment

    ReplyDelete
  6. Amazing Article ! I have bookmarked this article page as i received good information from this. All the best for the upcoming articles.

    TekSlate Online Trainings

    ReplyDelete
  7. Ovo je jedan od najboljih članaka ikada. Hvala vam što ste podelili. Želimo vam sreću i uspjeh!


    giảo cổ lam 5 lá

    giảo cổ lam 7 lá

    giảo cổ lam khô

    giảo cổ lam 9 lá

    ReplyDelete
  8. Ортақ әкімшінің арқасында. Сізге қызықты әрі қызықты мақалалар тіледі.

    lều xông hơi

    lều xông hơi giá rẻ

    lều xông hơi sau sinh

    lều xông hơi loại nào tốt

    ReplyDelete
  9. Vanskeligheter( van bi ) vil passere. På samme måte som( van điện từ ) regnet utenfor( van giảm áp ) vinduet, hvor nostalgisk( van xả khí ) er det som til slutt( van cửa ) vil fjerne( van công nghiệp ) himmelen.

    ReplyDelete

  10. It’s awesome that you want to share those tips with us. I assume lot of us that commented on this post are just starting to search for different ways of blog promotion and this sounds promising. This is definitely the article that I will try to follow when I comment on others blogs. Cheers
    Data Science Training in Hyderabad

    Hadoop Training in Hyderabad

    Java Training in Hyderabad

    Python online Training in Hyderabad

    Tableau online Training in Hyderabad

    Blockchain online Training in Hyderabad

    informatica online Training in Hyderabad

    devops online Training

    ReplyDelete
  11. Hello, Thanks for your Great post! I Get Satisfied reading it, you are a good author.I will Make sure to bookmark your blog and definitely will come back from now on. I want to encourage that you continue your great job, have a nice day.

    Seo Digital Marketing
    Digital Marketing In Hyderabad
    Digital Marketing Near Me
    Digital Marketing Expert
    Google Online Marketing Challenge

    ReplyDelete