Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Fall 2019

## JSON - Creating Content with jQuery

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"]};`
  The JSON data structure. An object with a single name/value pair (name is "seasons" and value is the array of 4 strings)
- `var seasons = mydata.seasons;`
  Create a variable `seasons` that is equal to `mydata.seasons`. At this point, the variable `seasons` is equal to `["Spring", "Summer", "Autumn", "Winter"]`
- `var ul_node = $('<ul>');`
  Use jQuery syntax to create a `ul` node,
- `for (var i in seasons) {`
  Iterate through the array via index position. Remember that arrays in JavaScript (as in almost all programming languages) begin with an index of 0. Therefore, the first time through this loop, `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>');`
  Use jQuery syntax to create an `li` node.
- `li_node.text(seasons[i]);`
  Set the text value of the `li` node to be the value of the array item (e.g. first time through the loop, this creates ``
- `ul_node.append(li_node);`
  Append the `li` node to the `ul` node (e.g. the first time through the loop, we will then have
- `}`
  this is the curly brace to close the close the loop started in `for (var i in seasons) {`
- `$('#seasons').append(ul_node);`
  Finally, once the `ul` is completed, we append it to the element whose id is `#seasons`

### All Together

- Seasons Example in JS Fiddle
- Seasons Example Standalone | download

Complete markup is:

Copyright © David Heitmeyer