Please enable JavaScript to view the comments powered by Disqus.

Parse JSON in JavaScript

In the previous post ( [Android] Parse JSON in Android ), I showed how to get the JSON string from server and parse it into desired object using Java. This time, in this tutorial, I’ll parse JSON in JavaScript. This can be applied when you develop an mobile application using PhoneGap.

A - jQuery.getJSON() method

JQuery provides a method call getJSON() to load the JSON encoded data from server using GET method.

Syntax:

jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )
  •  url: the string contains URL to call web service
  • data: the data you want to send to server (plain object or string format)
  • success: the callback function that will execute when request succeeds

The getJSON() method above is equivalent to below ajax method:

$.ajax({ 
  dataType: "json", 
  url: url, 
  data: data, 
  success: success 
});

 Remember to enconde all the data before submit to server side. Because they will be appended to the URL string.

B - Parse JSON in JavaScript demo

About the appearance, this demo is one HTML page with only one button - Demo getJSON()

When you click on the button, it’ll show the result. Simple, right?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> 
    <meta content="utf-8" http-equiv="encoding"> 
     
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
    <title>Demo JSON</title> 
     
    <script type="text/javascript"> 
        function demoClick(){             
            var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; 
              $.getJSON( flickerAPI, { 
                tags: "mount rainier", 
                tagmode: "any", 
                format: "json" 
              }, function( data ) { 
                  $.each( data.items, function( i, item ) { 
                    $( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" ); 
                    if ( i === 3 ) { 
                      return false; 
                    } 
                  }) 
            }); 
        }     
    </script> 
     
</head> 

<body> 
    <button id='btn_get' onclick='demoClick();' type="button">Demo getJSON()</button> 
    <div id="images"></div> 
</body> 

</html>

 

In this demo, I use a web service of Flickr that will return a list of public content matching some criteria.

This post has no images LOL =))

Done for today!

The whole source code is already in this post so I won’t upload it :)