Parse JSON from URL using jQuery

By Faruque Ahamed Mollick

JSON is an organized and lightweight data format that uses for data interchanging. There are many websites today are sharing data with JSON format. Primarily this type of data format used to transmit data between server and web application.

In this post, I am going to tell you how to parse JSON data that is given through an URL.

Send AJAX request every n seconds using jQuery



Before I go forward, let’s assume a link http://www.example.com/country-population-json which providing the JSON formatted data that contains some cities and it’s population in JSON format just like below:

{
"population_by_cities": {
    "Delhi": 14300000,
    "New York": 17800000,
    "London": 8278000,
    "Kolkata": 12700000,
    "Paris": 9645000
  }
}

We have taken it just for an example to show you how to parse JSON in jQuery.

After that let’s write some HTML code where the city name and population will be shown:

<h2>Population by cities</h2>
<p>Delhi: <span id="Delhi"></span></p>
<p>New York: <span id="NewYork"></span></p>
<p>London: <span id="London"></span></p>
<p>Kolkata: <span id="Kolkata"></span></p>
<p>Paris: <span id="Paris"></span></p>

In the above code, you can see that I have created span tag in front of each city name where I keep the id of each span tag as the city name.

Live word counter from HTML textarea in JavaScript

Now the magic will happen when we use our jQuery code to retrieve population of each city that are in the JSON formatted data.

Below is the jQuery code:

$(document).ready(function() {

$.ajax({
  dataType: "json",
  url: 'http://www.example.com/country-population-json',
  
  success: function(data) {
       //console.log(data['cities']);
       var city = data['population_by_cities'];
       //console.log(city);

       	  $("#Delhi").html(city['Delhi']);
       	  $("#NewYork").html(city['New York']);
       	  $("#London").html(city['London']);
       	  $("#Kolkata").html(city['Kolkata']);
       	  $("#Paris").html(city['Paris']);
      
    }
});

});

That’s it. Now we will be able to see the number in front of every city name as we have set the content inside those span tag by using jQuery html() method.

Here we have used jQuery AJAX to retrieve city population from the JSON formatted data. We have set the dataType as json and getting each data and add these data to the HTML tags after a successful call of AJAX.

Live word counter from HTML textarea in JavaScript

The ‘data’ is retrieving the complete JSON content. We have taken the data[‘population_by_cities’] in a variable city which contain each city name with the number of population as Integers. Then we are getting population for each city. For example, city[‘London’] contains the number of population of London.

I hope, you have got some idea on how to parse and retrieve JSON provided through an URL.

Leave a Reply

Your email address will not be published. Required fields are marked *