Monday, May 20, 2013

Windows 8 – Parsing JSON - The Twitter API

JSON format is used for serializing & transmitting structured data over network connection. Now as we’ve seen in the previous post Windows 8 - Downloading from the web, where we were downloading data from the web, in Windows 8. Here we were hitting my blog and what we were getting HTML content of my blog in return.

Now just for a second, imagine we, instead of hitting my blog post, hit a public api which return some data in JSON format. Then the data return won’t be HTML any longer, it will be a proper JSON serialized structured data, which we can parse to extract information. One of the most used API is the API which twitter provides to get tweets based on “hash tag”.

The API

Here is the api that we will be using:
http://search.twitter.com/search.json?q=%23Windows8&rpp=1000

The Code

API above, will give 1000 tweets which possess Windows8 as the hash tag, as simple as that. After retrieving tweets , which are in JSON format, we need to parse them. Here is how the code of the function getContentFromWeb of the previous post will change to:

   1: function getContentFromWeb() {
   2:        var link = "http://search.twitter.com/search.json?q=%23Windows8&rpp=1000";
   3:        WinJS.xhr({ url: link }).then(
   4:               function (responce) {
   5:                   var allHtml = document.getElementById("allHtml");
   6:                   var res = JSON.parse(responce.responseText);
   7:                   for (var i = 0; i <= res.results.length - 1; i++) {
   8:                       allHtml.innerText = allHtml.innerText + res.results[i].from_user;
   9:                   }
  10:               }
  11:           );
  12:    }

In line #6, we parsed the result that we got from the api. Now as being the result (tweets) in the JSON format, when we parse it, we get the array of tweets. So with the help of for loop, we iterates through the array, and display the name of the person who did that tweet on the screen. The UI though is not very good. But it serve the purpose.

So this is how, we can parse the result if it is in JSON format to a readable information.

Happy Reading!!!

Share this post

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top