DEV Community

Programming Liftoff
Programming Liftoff

Posted on

JSON Simplified

This article was originally published on programmingliftoff.com as JSON Simplified.

Website with JSON data

JSON is an essential part of the web today. It's unavoidable for anyone programming in JavaScript. JSON stands for JavaScript Object Notation. An AJAX request is used in JavaScript to request JSON data from a server. AJAX stands for Asynchronous JavaScript And XML. XML is a data format that used to be used instead of JSON, but today JSON has become dominant in this area. At the end of this tutorial we will have a simple local webpage that sends an AJAX request for JSON data that we upload to a server and then displays that data on the local webpage. Let's do it!
Note: If you learn better from videos, click here for a video walkthrough: JSON Simplified YouTube Video.

First let's take a look at some real JSON.

{
  "class": "Biology",
  "homework": "Memorize cell structure",
  "classId": 1
}
Enter fullscreen mode Exit fullscreen mode

As you can see, JSON looks like a JavaScript object (that must be why its called JavaScript Object Notation!). A few special notes about JSON are that all the object keys (class, homework, and classId in the above snippet) must be have double quotes around them. Also, if the value is a string it must have double quotes as well (single quotes are not valid). However, numbers do not and should not have double quotes surrounding them.

Alright, now that we've seen some JSON, lets have some fun!

I've uploaded some JSON to GitHub here: https://github.com/programming-liftoff/json-simplified/blob/master/jsondata.json. We're going to create a simple webpage that grabs the JSON data from the GitHub repo and displays it in the webpage. Sounds awesome, right!?

In your favorite text editor, create a file named index.html. In it past the following HTML:

<html>
<head></head>
<body>
  <div id='page-data'></div>
  <script>
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var pageData = '';
        var data = JSON.parse(xhttp.responseText);
        pageData = '<h1>' + data.student.name + '</h1>';
        pageData += '<h4>Let\'s learn some ' + data.class + '!</h4>';
        pageData += '<h4>For homework: ' + data.homework[0] + '</h4>';
        document.getElementById("page-data").innerHTML = pageData;
        console.log('Done!');
      }
  };
  xhttp.open("GET", "https://raw.githubusercontent.com/programming-liftoff/json-simplified/master/jsondata.json", true);
  xhttp.send();
  console.log('here')
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Then open that file in your browser. This can usually be done by double clicking the file in Finder or Windows Explorer. You can also try right clicking the file in your text editor, selecting "Copy Full Path", and pasting that path in your web browser (e.g., Chrome). You should now see the following webpage

Image of simple webpage displaying JSON data

Now let me explain what's going on here.

First, the line var xhttp = new XMLHttpRequest(); creates a new request object. The XML data format used to be more popular than JSON, but now JSON is used more and we are stuck with the name XMLHttpRequest. This object can be used to request JSON data from a file or server.

Let's skip down to line 21 xhttp.open("GET", "https://raw.githubusercontent.com/programming-liftoff/json-simplified/master/jsondata.json", true);. This line specifies the type of request we want to send. We're sending a GET request, since we want to get data from the server. The other option is POST, which could send data to the server. Next we specify the location of the JSON data. In this case its in a GitHub repository. Finally, we pass true. This means the request should be performed asynchronously. Performing the request asynchronously is the preferred method, since it allows the rest of the web page to load while the request is waiting for a response from the server with the data. This is therefore an AJAX (Asynchronous JavaScript and XML) request. Although as stated before, since we're using JSON in place of XML, you can think of it as an AJAJ request. Just go with the flow and call it AJAX though, because that's what everyone calls it (so it must be right, right?). Also note that xhttp.send(); is needed to actually send the request.

Now let's look at the xhttp.onreadystatechange function on line 7. The first line in that function is an if statement if (this.readyState == 4 && this.status == 200). This is saying that the code inside the if statement should be executed when the state of the request changes to 4, and the status is 200. A ready state with the value 4 means that the request has completed, and a status of 200 means that the request was successful. In other words, we have received the JSON data. Checkout Mozilla's post and W3School's post for more information about ready states and HTTP status codes respectively.

Finally on line 11, the line var data = JSON.parse(xhttp.responseText); retrieves the JSON response, uses JSON.parse to convert the response String to a JSON object, and stores that JSON object in the data variable. The object can now be used as a JavaScript object and the data can be shown on the web page.

Bonus:

Try changing true in line 21 to false, then refresh the page. Did you notice any change? There isn't any noticable change in the web page. But open the console (in Chrome, right click on the web page, select 'Inspect', and click on the 'Console' tab). And refresh the page again. You'll notice the order of the console.log statements changes. This is because when the call is not asynchronous (false), the page waits for the request to complete before continuing. Therefore 'Done!' prints before 'here'. When the call is asynchronous, the page sends the request and has time to print 'here' before the server responds to the request.

You may also notice a warning in the console when the parameter is set to false. This is the browser telling you that it's not a good idea to do this since the page loads slower if it's not asynchronous!

There you have it, you've now learned JSON and played around with AJAX. I will leave you with this challenge. Create a free account with GitHub if you don't have one. Then create a new repository and copy the JSON data from this tutorial into a file in that repository. Next, click the 'Raw' button to get the URL to the raw JSON data. Finally update the URL in line 21 to your URL. You're now pulling JSON from your GitHub server space to your web page. Awesome!

Now go ahead and modify the JSON and the web page to play around with it some more. And feel free to post a comment below if you publish you're site live so that others can view it and be inspired!

Get stuck anywhere, or want to hear everything explained again in a video? Click the following link for a nice video walkthrough of all these steps! JSON Simplified YouTube Video

Thanks for reading!

-Andrew @ Programming Liftoff
Website: programmingliftoff.com

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.