Parse JSON data using jQuery.getJSON()

In this post I am going to explain, how we can parse a JSON data which we will get here using one of the jQuery Ajax shorthand method$.getJSON(). Basically, the $.getJSON() method loads the JSON-encoded data from the server using a GET HTTP request based on a URL to which the request is sent. It also has a callback function which is executed if the request succeeds. The returned data passed to the callback function is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. So, we don’t need to worry about if the data returned from the server is an integer, string or else, since it’s always a JSON-encoded data.

Now, lets see an example to make things more clear. For this, I am going to use a URL from the Google Geocoding API. This API is mainly used for the Geocoding purpose, which is the process of converting addresses into geographic coordinates, which you can use to place markers or position the map. And the URL is:

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true

If we open this URL in a new browser window and hit enter, we will see that a JSON-encoded data is returned from the server.

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Amphitheatre Parkway",
               "short_name" : "Amphitheatre Pkwy",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara",
               "short_name" : "Santa Clara",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94043",
               "short_name" : "94043",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.42141110,
               "lng" : -122.08403720
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.42276008029150,
                  "lng" : -122.0826882197085
               },
               "southwest" : {
                  "lat" : 37.42006211970850,
                  "lng" : -122.0853861802915
               }
            }
         },
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

Now, we will primarily focus here on getting the values for the keys: formatted_addresslat and lng. Where,

  • formatted_address is a string containing the human-readable address of this location.
  • lat is the geocoded latitude value.
  • lng is the geocoded longitude value.

Now, we can get these values using jQuery like this:

var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";

$.getJSON(geocodingAPI, function (json) {
    var address = json.results[0].formatted_address;
    console.log('Address : ', address);

    var latitude = json.results[0].geometry.location.lat;
    console.log('Latitude : ', latitude);

    var longitude = json.results[0].geometry.location.lng;
    console.log('Longitude : ', longitude);
});

Explanation:

  1. Code in the first line
    var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
    

    Here, in the above code, we are setting the URL string as a global variable geocodingAPI.

  2. Code in the third line
    $.getJSON(geocodingAPI, function (json) {
    

    In the above code, we are calling the $.getJSON Ajax method and passing the geocodingAPI url string containing the URL to which the request is sent to the server. On successful execution, a JSON-encoded data is returned from the server as variable named json here.

  3. Code in the fourth and the fifth line
    var address = json.results[0].formatted_address;
    console.log('Address : ', address);
    

    The Google Geocoding API returns results and it places them within a (JSON) results array. Now, we can get the results array using the JavaScript Object dot notation like json.results, where results is the key of the json object returned. This will return all the objects in the array but since the results array has only one object, we can just do this json.results[0] and it will return the first object in the array.

    Again, using the Object dot notation, we can get the formatted_address key value like json.results[0].formatted_address. Now, using the code in the next line console.log('Address : ', address);, we can check in the browser console what value we are getting. If you open your browser console, you will be able to see the value like this:

    Address :  1600 Amphitheatre Parkway, Mountain View, CA 94043, USA
    

    F.Y.I. The above is the address of Googleplex, the corporate headquarters complex of Google.

  4. Code in the next few lines
    var latitude = json.results[0].geometry.location.lat;
    console.log('Latitude : ', latitude);
    
    var longitude = json.results[0].geometry.location.lng;
    console.log('Longitude : ', longitude);
    

    Now that we are bit familiar with the JavaScript Object dot notation, you probably have figured out by now, what will be the output of the above code and what it does. But, in case you have not, let me explain. Since the lat key is nested within the location object, which again is nested within the geometry object, we will have to use the json.results[0].geometry code first to get the geometry object and then the json.results[0].geometry.location code to get the location object.

    And finally we will use the json.results[0].geometry.location.lat code to get the lat key value and similarly we will get the lng key value too. Again, if you open your browser console, you will be able to see the values like this:

    Latitude :  37.4214111
    Longitude :  -122.0840372
    

Demo:

  • Working Demo on jsFiddle #1
    ( For full screen result, open this. In this fiddle, I have parsed the JSON data and set the results as the table cells text. I have also provided the URL, so that you can click it and see the JSON encoded result in a new window. )
  • Working Demo on jsFiddle #2
    ( In case, you are bit more interested to see the code, open this. )

That’s it. 🙂 Hope, I have been able to make things clear. If you have any comments or suggestion or any queries about this post please add it in comments section. I would really appreciate it.

Happy Coding 🙂

Advertisements

47 thoughts on “Parse JSON data using jQuery.getJSON()

  1. Hello There. I found your blog using msn. This is a really well written article.
    I will make sure to bookmark it and return to read more of your useful information.
    Thanks for the post. I’ll certainly comeback.

  2. This piece of writing offers clear idea in favor of the new
    people of blogging, that truly how to do running a blog.

  3. hi, can i parse json data whichever located in [
    For example: “address_components” : [
    {
    “long_name” : “1600”,
    “short_name” : “1600”,
    “types” : [ “street_number” ]
    },
    {
    “long_name” : “Amphitheatre Parkway”,
    “short_name” : “Amphitheatre Pkwy”,
    “types” : [ “route” ]
    },
    {
    “long_name” : “Mountain View”,
    “short_name” : “Mountain View”,
    “types” : [ “locality”, “political” ]
    },
    {
    “long_name” : “Santa Clara County”,
    “short_name” : “Santa Clara County”,
    “types” : [ “administrative_area_level_2”, “political” ]
    },
    {
    “long_name” : “California”,
    “short_name” : “CA”,
    “types” : [ “administrative_area_level_1”, “political” ]
    },
    {
    “long_name” : “United States”,
    “short_name” : “US”,
    “types” : [ “country”, “political” ]
    },
    {
    “long_name” : “94043”,
    “short_name” : “94043”,
    “types” : [ “postal_code” ]
    }
    ]

  4. I have a similar problem. But because the number of address components can vary, I cannot rely on getting the right component if I use the array index. The results[0] index is fine, that’s just the most likely match in the unlikely event there is more than one result returned, but the index for address components will differ if the address has an apartment number and a street number for example.

    What would the syntax be to extract the ‘postal_code’ and ‘locality’ address_components when their index position is unknown?

  5. Hi Thank you for the blog, it helped me alot, i have another question pls help me out. How to get the address_components in each row depending on the number . Here in example long-name, short-name and type to be in one single row , need to get 7 rows in this scenario

    • Hi Sunitha,

      Thanks so much for your response. Regarding your question, please check out this fiddle demo here for full screen result and if you want to see the code you can check it here. Let me know if you need any further help!

      Thanks,
      Palash

    • Hi Sunitha,

      Thanks so much for your response. Glad that jsFiddle demo help you. You can also look into my other blogs on jQuery as well, if you like 🙂

      Thanks,
      Palash

  6. Hi Palash,

    Need ur help urgent pls repy ASAP.

    I got response as “list_components” : [
    {
    “ID” : “1”,
    “entity” : “permit-type”,
    “status” : “X03”,
    },
    {
    “ID” : “2”,
    “entity” : “permit-status”,
    “status” : “M03”,
    },
    {
    “ID” : “3”,
    “entity” : “permit-type”,
    “status” : “Q03”,
    },
    {
    “ID” : “4”,
    “entity” : “permit-status”,
    “status” : “p03”,
    }

    ],

    In this i need to get elements (status) of “entity” : “permit-type” means here permit-type is in two times and having 2 status X03 and Q03 . Need to get values of status which having entity permit-type.

  7. Hi Palash,

    This is what i need, thank you so much for ur demo. Will be back of you for any doubt :-).

    Thank You,
    Sunitha.B

  8. Hi Palash,

    I’m working with a json API that looks like the one you have used but I got probably a syntax problem. My API is like this:

    {
    “0”:
    {
    “ad”: “123”,
    “type”: “xxx”,
    “title”: “title1”
    }
    }

    Here’s for sure the error:

    var type = json.0[0].type;
    console.log(‘Type : ‘, type);

    • Hi Padhu,

      Thanks so much for your response. Actually, I am going to start writing blogs on AngularJS soon, but not on this site. It would be a new domain. I will keep you updated on that. Do subscribe to this blog so that you get a notifications mail about that.

      Thanks,
      Palash

  9. Hi, I need help. How I have a decode this array:

    {“songs”:{“refresh”:78,”last”:{“id”:”9007859″,”interpret”:”TOM\u00c1\u008a KLUS”,”skladba”:”Kdy\u009e si t\u00ec, d\u00edvko, p\u00f8edstav\u00edm”},”now”:{“id”:”9006331″,”interpret”:”GERI HALLIWELL”,”skladba”:”It’s Raining Men”},”next”:{“id”:”9007789″,”interpret”:”GEORGE EZRA”,”skladba”:”Budapest”}}}

    This array if from page: http://www.hitradioorion.cz/export/now-playing/.

    The good by was decode in html page.

    Thanks for help.

  10. Hello, I am trying to run it in my localhost. I created a view form and copy the html to it and then I created a new form named control.js and copy the javascript code. But unfortunately it didn’t run. Am I doing right or I am wrong. Please help. 😦 I want to figure out this.

    • Hi Cristina,

      First of all, thanks so much for your response. Next regarding your issue, I would like to know if you have included the jquery file too or not to the new page along with the new control.js file?

      Looking forward to your response.

      Thanks,
      Palash

  11. Thanks for your quick reply, yes they are all in one folder.
    for html- view.html
    for javascript-control.js
    for css-design.css

    I am beginner in json and jquery so I don not have a enough knowledge to figure out this on my own. How can I included the jquery file along with new control.js file?
    In my view.html I added this line below:

    but nothing works. By the way to make it clear follow the link here and you will see the ouput.

    Looking forward to your response.
    Thank you so much! 🙂

    • Hi Cristina,

      I have created a demo including all the necesssary js files(jquery, script.js). I have renamed control.js file to script.js in the demo. Also, I have included the jQuery file from an external source. You can also download the jQuery js file and load it from local or use a CDN file. Here is the …DEMO….

      Looking forward to your response.

      Thanks,
      Palash

  12. Hi Palash,

    I followed what you did and it’s awesome it did work. . I knew what is my fault, I didn’t include the jquery file. Sorry I am a begginer, Thank you so much for your article, this is a big help for us.

    regards,
    cristina

    • Hi Cristina,

      I am so glad that the demo helped you in understanding your problem correctly. I hope in future you would be able to resolve such kind of issues by yourself. Till then Happy Coding 🙂

      Thanks,
      Palash

  13. What i do not realize is in reality how you are not actually much more smartly-liked than you may be now. You’re very intelligent. You understand thus significantly when it comes to this subject, produced me in my opinion consider it from a lot of varied angles. Its like men and women are not involved except it’s one thing to do with Woman gaga! Your personal stuffs great. Always handle it up!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s