JSON Simplified
Tags: json, programming, webdev, beginners
Published: 2018-03-08 05:51:39

---
title: JSON Simplified
published: true
description: Want to learn JSON?  Then this tutorial is for you!  In this tutorial we will create a webpage that requests JSON data from a server and brings it to our webpage to be displayed.  We will use GitHub to host the JSON data, for free :).

tags: JSON, programming, webdev, beginners
---

*This article was originally published on [programmingliftoff.com](http://programmingliftoff.com/) as [JSON Simplified](http://programmingliftoff.com/json-simplified/).*

![Website with JSON data](https://thepracticaldev.s3.amazonaws.com/i/xf8uquh4inpw27s1b0z7.png)


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](https://youtu.be/dK90uu-nycA)._

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

```json
{
  "class": "Biology",
  "homework": "Memorize cell structure",
  "classId": 1
}
```

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 <em>index.html</em>.  In it past the following HTML:
```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>
```

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

<img src="http://programmingliftoff.com/wp-content/uploads/2018/02/json-simplified-webpage.png" alt="Image of simple webpage displaying JSON data" width="483" height="239" class="size-full wp-image-293" />

Now let me explain what's going on here.  
First, the line <code class=language-JavaScript>var xhttp = new XMLHttpRequest();</code> 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 <code class=language-JavaScript>xhttp.open("GET", "https://raw.githubusercontent.com/programming-liftoff/json-simplified/master/jsondata.json", true);</code>.  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 <code class=language-JavaScript>xhttp.send();</code> is needed to actually send the request.

Now let's look at the <code class=language-JavaScript>xhttp.onreadystatechange</code> function on line 7.  The first line in that function is an if statement <code class=language-JavaScript>if (this.readyState == 4 && this.status == 200)</code>.  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 <a href='https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState' target='_blank'>Mozilla's post</a> and <a href='https://www.w3schools.com/tags/ref_httpmessages.asp' target='_blank'>W3School's post</a> for more information about ready states and HTTP status codes respectively.

Finally on line 11, the line <code class=language-JavaScript>var data = JSON.parse(xhttp.responseText);</code> retrieves the JSON response, uses <code class=language-JavaScript>JSON.parse</code> 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.

<h3>Bonus:</h3>
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 <code class=language-JavaScript>console.log</code> 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 <a href='https://github.com/' target='_blank'>GitHub</a> 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](https://youtu.be/dK90uu-nycA)

Thanks for reading!

-Andrew @ Programming Liftoff
**Website:** [programmingliftoff.com](https://programmingliftoff.com)