JSON – using the basics

Hi again. This article is a follow on from another that I wrote about the basics of JSON. If you are new to JSON, I suggest you give this article a good read first. It gives some basics on JSON format and some descriptive examples. Be sure to come back though and we will get stuck into JSON.

So, here we are with some JSON knowledge and nothing to do with it. To make it more applicable, I will explain how I regularly use JSON through a real-life example. The scenario is that we have an HTML select element (dropdown lists). Let's call it - Continent.

Here is the dropdown list data.

Continent
ID Name
AU Australia
SA South America
AS Asia
EU Europe
AF Africa
NA North America

Notice that we have a list of continents (ID and Name). What we will do is load the continent data into a dropdown list on the page.

How do we do this?

Firstly, let's build our JSON stream. In this article, we are creating and consuming the JSON stream but, more often than not, the JSON data will come from a database. You can get this in a number of different ways and I'll describe that in another article.

$(function () {

    //  Let's build a JSON stream (client-side recordset)
    var json = { "continent":
    [
        { "id": "AU", "name": "Australia", "email": "brisbane@mycompany.com;" },
        { "id": "CA", "name": "Canada", "email": "canada@mycompany.com" },
        { "id": "SA", "name": "South America", "email": "chile@mycompany.com" },
        { "id": "AS", "name": "Asia", "email": "singapore@mycompany.com" },
        { "id": "EU", "name": "Europe", "email": "czechrepublic@mycompany.com" },
        { "id": "AF", "name": "Africa", "email": "johannesburg@mycompany.com" },
        { "id": "NA", "name": "North America", "email": "usa@mycompany.com" }
    ]
    }
}

So now let's populate the Continent select box. As I mentioned earlier, we already have a select box in the HTML with an ID of Continent.

$.each(json.continent, function () {
$("#continent")
      .append(
          $("")
          .attr("value", this.id)
          .text(this.name)
      );
});

What is happening here? Well, this code is stepping through each item in the JSON data list. As we step through each item, we add a new item to the the Continent element. In this example, I've added the ID text as the option value and the Name as the option Text. But you could change that. You can insert the Name text as the option Value and the Email text as the option Text. You just switch around the JSON fields like this.

$.each(json.continent, function () {
$("#continent")
      .append(
          $("")
          .attr("value", this.name)
          .text(this.email)
      );
});

This example will display the email address in the dropdown list and the Name will be the text that is sent in a form post. That's cool, right?

Til next time ....