26.5. Exercises

26.5.1. JSON

  1. Which of the following three code snippets is correct JSON syntax? Why are the other two options incorrect?

    1. {
         type: "dog",
         name: "Bernie",
         age: 3
      }
      
    2. {
         "type": "dog",
         "name": "Bernie",
         "age": 3
      }
      
    3. {
         "type": 'dog',
         "name": 'Bernie',
         "age": 3
      }
      

    Check your solution.

  2. Which of the following three code snippets is correct JSON? Why are the other two options incorrect?

    1. {
         "animals": [
            {
                  "type": "dog",
                  "name": "Bernie",
                  "age": 3
            },
            {
                  "type": "cat",
                  "name": "Draco",
                  "age": 2
            }
         ]
      }
      
    2. {
         [
            {
                  "type": "dog",
                  "name": "Bernie",
                  "age": 3
            },
            {
                  "type": "cat",
                  "name": "Draco",
                  "age": 2
            }
         ]
      }
      
    3. [
         {
               "type": "dog",
               "name": "Bernie",
               "age": 3
         },
         {
               "type": "cat",
               "name": "Draco",
               "age": 2
         }
      ]
      

26.5.2. Fetch

To practice fetching data, create a file called fetch_planets.html using touch in your terminal.

Add this preliminary HTML to your fetch_planets document:

 1<!DOCTYPE html>
 2<html>
 3   <head>
 4      <title>Fetch Planets</title>
 5      <script>
 6         window.addEventListener("load", function(){
 7            // TODO: fetch planets JSON
 8         });
 9      </script>
10   </head>
11   <body>
12      <h1>Destination</h1>
13      <div id="destination">
14         <h3>Planet</h3>
15      </div>
16   </body>
17</html>
  1. The URL where our planet data is located is: "https://handlers.education.launchcode.org/static/planets.json". Add the code to fetch this URL inside the load event listener.

    Check your solution.

  2. Peek at the response returned in the request by adding a print statement inside of the function.

    Copy the file path of your HTML file and paste it as the URL in your browser. You won't see much on the page yet. Open your developer tools and examine both the Console tab for the response value, as well as the Network tab for the request status.

  3. Use the .json() method on your response now to see more of the data in the console: What data type do you see printed?

    Check your solution.

  4. Replace your console.log(json) with the following to view a portion of the JSON into the app.

    1const destination = document.getElementById("destination");
    2destination.innerHTML = `<h3>Planet ${json[0].name}</h3>`;
    

    Refresh the page to see some new data in your HTML. Play around by changing the index number. Does the planet name change? Can you change the planet's property being printed?

  5. Now, what happens if we move those last lines we added to outside and after the fetch request?

    Since json hasn't been defined outside of the response.json() method yet, in order to move the template literal that uses that json variable, we'll need to initiate it outside of the function call. Let's also put our print statement back so we can verify that our fetch works.

    Refresh the page and try this. See any data? See anything of note in the console?

    Check your solution.

  6. Our last task left us with some knowledge about where and how we can use the fetched data, but we don't really want to keep those changes. Instead, how about we use an event to change the planet information we see? Let's move the DOM manipulation to inside a click handler.

     1fetch("https://handlers.education.launchcode.org/static/planets.json").then(function(response){
     2   response.json().then(function(json) {
     3      const destination = document.getElementById("destination");
     4      destination.addEventListener("click", function(){
     5         destination.innerHTML = `
     6            <div>
     7               <h3>Planet ${json[0].name}</h3>
     8               <img src=${json[0].image} height=250></img>
     9            </div>
    10         `;
    11      });
    12   });
    13});
    

    Now, after refreshing the page, you can click on the Planet header to make the name and image appear. Take note, we're still fetching on load, just not displaying the data until the the header is clicked.

  7. For fun and good measure, let's dynamically change which planet's info we're displaying each time the header is clicked. To do this,

    1. Declare a counter variable, index that changes each time a click event takes place.
    2. Use the value of index as the position in the planets array to use in the template literal.
    3. Finally, since we want to cap the value of index so that it does not exceed the length of the planets array, use a modulo to control how large index can get.

    Et voila! Our destination changes on each click!

    Check your solution.

    Clicking through destinations.

    Put on your planetary shoes. We are moving through planets!