freeCodeCamp Challenge Guide: Convert JSON Data to HTML

Convert JSON Data to HTML


Solutions

Solution 1 (Click to Show/Hide)
<script >
  document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('getMessage').onclick = function() {
      req = new XMLHttpRequest();
      req.open("GET", '/json/cats.json', true);
      req.send();
      req.onload = function() {
        json = JSON.parse(req.responseText);
        var html = "";
        // Add your code below this line

        json.forEach(function(val) {

          // Adding each object keys
          var keys = Object.keys(val);
          // Generating new html
          html += "<div class = 'cat'>";
          // Adding the custom html to each key
          keys.map(function(key) {

            html += "<strong>" + key + "</strong>: " + val[key] + "<br>";

          });

          html += "</div><br>";

        });

        // Add your code above this line
        document.getElementsByClassName('message')[0].innerHTML = html;
      };
    };
  });
</script>
<style>
  body {
    text-align: center;
    font-family: "Helvetica", sans-serif;
  }
  h1 {
    font-size: 2em;
    font-weight: bold;
  }
  .box {
    border-radius: 5px;
    background-color: #eee;
    padding: 20px 5px;
  }
  button {
    color: white;
    background-color: #4791d0;
    border-radius: 5px;
    border: 1px solid #4791d0;
    padding: 5px 10px 8px 10px;
  }
  button:hover {
    background-color: #0F5897;
    border: 1px solid #0F5897;
  }
</style>
<h1>Cat Photo Finder</h1> 
<p class="message box">
  The message will go here
</p>
<p>
  <button id="getMessage">
    Get Message
  </button>
</p>
11 Likes

hey bro i’m trying the same but “The message box should have something in it.
” this error is comming

The naming of “val” is truly confusing, I suggest you name it “obj”. Check my code.
“JSON APIs and Ajax” is too compact and confusing. If you would expand it and teach it slowly it will be understandable. It’s the third time I’m doing these 7 exercises over and yet I don’t know how to connect the nodes in my mind to “Building a Random Quote Machine”.

9 Likes

Check https://www.freecodecamp.com/json/cats.json ; Really guys? Each of those objects inside the json does not seem to me like a “val”.
I fact each object contains 3 keys and values paired to them, and those end values should be called “val”.

And increase comment autosave time, it’s really annoying. Doesn’t let me focus on what I wanna say.

saving…
saved

saving…
saved

…

Needed more explanation but got code here instead

What does this mean : var keys = Object.keys(val); ??

3 Likes

This is confusing, can someone explain whats goin here

6 Likes

Take a look at this

3 Likes

I will. Thank you :slight_smile: