Now that we have a sense of JSON and its "object" and "array" structures, let's see how we can create content from JSON using JavaScript.
We'll use the jQuery JavaScript library to build up markup based on data in the JSON structure, and then we'll place it on the page.
We'll use the "seasons" array to build an unordered list of seasons.
The JSON data:
The result we will build:
Let's take a look at the important parts:
HTML:
JavaScript:
var mydata = {"seasons":["Spring", "Summer", "Autumn", "Winter"]};
var seasons = mydata.seasons;
seasons
that is equal to mydata.seasons
. At this point, the variable seasons
is equal to ["Spring", "Summer", "Autumn", "Winter"]
var ul_node = $('<ul>');
ul
node,for (var i in seasons) {
i
will be 0
, the second time, i
will be 1
, etc. And to access the value of the array, seasons[i]
will be used — seasons[0]
is Spring
and seasons[1]
is Summer
, etc.var li_node = $('<li>');
li
node.li_node.text(seasons[i]);
li
node to be the value of the array item (e.g. first time through the loop, this creates 
ul_node.append(li_node);
li
node to the ul
node (e.g. the first time through the loop, we will then have }
for (var i in seasons) {
$('#seasons').append(ul_node);
ul
is completed, we append it to the element whose id is #seasons
Complete markup is:
Copyright © David Heitmeyer