Getting JSON data in jQuery

We saw earlier that we can use the get method to get data in json format. However, the jQuery library also provides a special getJSON. This method sends a GET request to the server and receives json data in response.

This method accepts the following parameters:

  • url: required parameter containing the address of the resource that the request will access
  • data: optional parameter containing a simple javascript object or string to be sent to the server along with the request
  • success(data, textStatus, jqXHR): An optional parameter that represents a callback function that will be executed when the request succeeds.

On output, the getJSON method returns the object jqXHRassociated with the current request.

Let’s say on the server we have the following file countries.json , which contains a list of countries in json format:

{
    "Great Britain": 1,
    "China": 2,
    "Russia": 3,
    "USA": 4,
    "France": 5
}

Let’s add a drop-down list (element select) to the page and load data from this file into it:

<select id="countries">
    <option disabled>Select country</option>
</select>
<script type="text/javascript">
$(function(){
    $.getJSON('countries.json', function(data) {
                $.each(data, function(key, val) {
                    $('#countries').append('<option value="' + val + '">' + key + '</option>');
                });
    });
});
</script>

url The name of the json file is used as the parameter value . Since the incoming data is a set, we can iterate over it in an each loop and apply a processing function to it.

The handler function is called for each element in the set and takes two parameters: a data name or a key (key) and a value (val). That is, in the string “Россия”: 3″Russia” is the key, and 3 is the value.

In this case, our data structure is quite simple. Now let’s look at using data with a more complex structure. For example, we have a users.json file defined like this :


{
    "users": [{
        "id" : 1,
        "name": "Bill Gates",
        "age": 43
    }, {
        "id" : 2,
        "name": "Sergey Brin",
        "age": 33
    }, {
        "id" : 3,
        "name": "Larry Page",
        "age": 34
    }]
}

Let’s try to display it in a table on the page:

<table id="users">
    <tr><td>Id</td><td>Name</td><td>Age</td><tr>
</table>
<script type="text/javascript">
$(function(){
    $.getJSON('users.json', function(data) {
            for(var i=0;i<data.users.length;i++){
                $('#users').append('<tr><td>' + data.users[i].id + '</td><td>' + data.users[i].name +
                '</td><td>' + data.users[i].age + '</td><tr>');
            }
    });
});
</script>

Using the property names of json objects, we can access them (for example, data.users[i].age) and thereby display their values ​​on the page.