What do you want to learn?
Skip to main content
by Paul Cheney
Learn to leverage the power of AJAX to access and display JSON data from your local server, as well as from an external site using an API. You'll also learn how to create JSON files.
Resume CourseBookmarkAdd to Channel
Table of contents
In this module, we will demonstrate how to create and access JSON data. First, we will convert a string to an object and then an object back to a string. Next, we'll build a single-level JSON object and then build a two-level-deep object, and finally, a three-level object. In each of these, we'll also practice displaying the data. When we get data from a server, it comes as a string, and we use parse to convert it to a JSON object. Likewise, when we're trying to send JSON data through a URL, we must first convert the object to a string using stringify. Now let's switch gears and talk about structuring JSON. Here's the basic building block of JSON. To this, I will ads name- value pairs, and it will look like this when we actually add words. However, for now, we're going to leave them out to keep this example simple. Any value can be replaced by another series of data to make it two levels deep. Let's remove the double quotes from the second value and spread it apart. Now we can add another set of curly braces with name-value pairs in that space. We could do it again by taking out another value, spreading it apart, and dropping in yet another set of curly braces. Now we have one that is three levels deep. Although I have used three name-value pairs in each example, there's really no limit to how many you can use in the real world. Yeah, this stuff can get pretty complex. Let's try it out in an editor.
Single Level JSON Data
Now that you're able to convert from a string to an object and back, let's create another one called theData1, and we'll assign it as string with a name-value pair for first, another name-value pair for last, and another name-value pair for city. We want to then create a new variable called myObj, and we'll set it equal to JSON.parse, and we'll throw the data in there, and we'll take that and display it to the console just to test our work with myObj. Save it, come over here, we can see that our name-value for first, last, and city is all in place and working correctly. Now back in my index page, I have a paragraph that's currently empty, but it has an ID of message. So we're going to use that and display the contents of our JSON object into that. Let's come over here and we'll do document.getElementById. In this case it's message, and then we'll set the .innerHTML = myObj, and then you can use any of the names from the JSON object, which is first, last, or city, so let's try last. We'll save it. There's Cheney. If we add city, and then the city appears in that paragraph.
Double Level JSON Data
Here we're going to have an example once again, two name-value pairs. In this case we've got Jane and Jim. Let's first of all create a variable called myObj. Once again we'll set it to JSON.parse, and this time it's theData2, and then we'll display this, console.log as myObj. Save it, and there we go. Now we're going to take this value of tall, wipe it out, and provide some other characteristics about Jane. So remember the base. Let's come down here just to keep our code clean. Open closing curlies, name:value, name:value. And you don't put a comma after the last one or you'll break it. So let's copy that, and where those two quotes were, we're going to paste it. Do the same thing with Jim and chubby, delete the value and paste the combination. Now, what do we want to know about Jane? Well, maybe Jane has an age, and she's 29 forever, and maybe she has a degree from college that's an MFA. Jim over here also has an age. He admits he's 49, and he has a degree, and it's a master's. Delete this placeholder down here, save it, there's our object. Notice it has sub-objects in it because now we're at two levels deep. So how do we access these? Well, it sort of gives you a hint. If you mouse over age, you'll see .Jane.age or .Jane.degree. Document.getElementById, and we have message as an ID on the screen, and we'll set the .innerHTML = myObj.Jim.age. Let's see if that works, and sure enough, there's 49. And we could change this to Jane and get her age as 29 forever. So if you have very complex data, which we will look at in the last unit, you'll be able to open these things up, and by simply mousing over them, the console in Chrome will tell you what you need to do using .notation to display that particular value.
Triple Level JSON Data
Loading External JSON Data
Exploring the XMLHttpRequest Readystate
Exploring the XMLHttpRequest Onload and Status
Structuring JSON Data
So far, we have played around with basic JSON data, and now we're going to go deeper by adding arrays. In this module, we will look at three examples of how to include arrays in JSON data. Then we'll build and load an external JSON example for each one. Finally, we will put our JSON skills to use and build a JSON-driven hospitality web page. In our first example, we will put name-value pairs inside an array. Remember this basic building block for JSON data from module 2? Well, we're going to use it again. In our external JSON file, we will start with open and closing square brackets. Then we can add as many of these basic JSON building blocks as we want. They must be separated from each other using a comma. Remember not to add a comma after the last one, or it will break. In our second example, we will replace the value of a name-value pair with an array. First, we will delete the value and insert some space. Next, we will add square brackets, and then inside that, we can add basic JSON building blocks. Here's the same information presented vertically. We can easily add additional elements to an array. Remember to separate them with commas, and don't add a comma after the last one or it will break. In our last example, we will replace the value of a name-value pair with an array, remove the quotes, and add square brackets. In this case, we will add an array of values instead of name-value pairs. I promised at the beginning that we would build a weather app, and we will do that in the next module. However, at the end of this module, we will be practicing our JSON skills to build a hospitality page. All of the information for each room will come from a JSON object and be updated without reloading the page. So, let's get started.
Create Array JSON Presidents
Load Array JSON for Presidents
In our JSON data, we'll begin with a variable called xhr, and we'll set it equal to a new XMLHttpRequest. Then we will open it, and we're going to need three pieces of data. The first one is GET, the second one is the path, and the last one is true, which means load it asynchronously, which is the whole point of AJAX. To make sure everything is loading correctly, we will ensure the responseType is equal to text, and then we'll switch it to an object. Now that everything's set up, we can go ahead and issue the send, and because we're using GET on line 4, we don't need to put anything in here, semicolon. Now that's all going to happen in the background. Now we need to watch for the onload function. Well, first of all, we need to make sure that it was a successful load. If the xhr.status, equal to 200, which means it was successful, if it's successful, then we'll create a variable called myStuff, and we will assign it the JSON.parse of the xhr.responseText. And then to see what we're doing, we'll run that through the console. We can see here in our console that we have an object. It has elements 0, 1, and 2, which correspond to 0, 1, and 2. If we open object 1, we can see that it has 3 name-value pairs, a first, a last, and a served. And the others display the same way. So we have successfully loaded an array of JSON data with three different presidents. Let's track some of this information that we've just loaded. Let's first ask for myStuff, and because it's an array, we use array notation with brackets, and we can ask for 0, 1, or 2. If we ask for 1, it's going to give us the second president, which was John Adams. And if we were to ask for 0, of course, that should give us George Washington. Well, what if we add a .first? It should now give us the first name of the first element, which is George, and there it is. Of course, we could go last, and we get Washington. Remember, you can look at these in the console by mousing over any name, and it will show you exactly how to get it. It shows a 0.served or, in this case, a 1.served. So it's kind of helpful if you're trying to figure out complicated data to just mouse over and look at the path there, and them mimic that path right over here.
Load Named JSON for Presidents
Display Named JSON for Presidents
Load JSON Hospitality Data
Display JSON for Hospitality Page
Final Project: Weather Site
Getting the External JSON Data
Displaying the Current Conditions
Displaying the Three Day Forecast
Modification to Display Any Zip Code
Final Project: Weather Site II
Current Weather Conditions
Adding Forecast Information
Paul Cheney is a professor of Web Design and Development at Utah Valley University, where he teaches Responsive Design. He also owns his own web design company, which allows him to keep current in...
Released20 Mar 2017