Convert JSON Data to HTML
Now that you're getting data from a JSON API, you can display it in the HTML.
You can use a forEach
method to loop through the data since the cat photo objects are held in an array. As you get to each item, you can modify the HTML elements.
First, declare an html variable with let html = "";
.
Then, loop through the JSON, adding HTML to the variable that wraps the key names in strong
tags, followed by the value. When the loop is finished, you render it.
Here's the code that does this:
let html = '';
json.forEach(function (val) {
const keys = Object.keys(val);
html += "<div class = 'cat'>";
keys.forEach(function (key) {
html += '<strong>' + key + '</strong>: ' + val[key] + '<br>';
});
html += '</div><br>';
});
Note: For this challenge, you need to add new HTML elements to the page, so you cannot rely on textContent
. Instead, you need to use innerHTML
, which can make a site vulnerable to cross-site scripting attacks.
Add a forEach
method to loop over the JSON data and create the HTML elements to display it.
Here is some example JSON:
[
{
"id": 0,
"imageLink": "https://cdn.freecodecamp.org/curriculum/legacy-json-apis-ajax/funny-cat.jpg",
"altText": "A white cat wearing a green helmet shaped melon on its head. ",
"codeNames": ["Juggernaut", "Mrs. Wallace", "Buttercup"]
}
]
Tests
- Waiting: 1. Your code should store the data in the
html
variable - Waiting: 2. Your code should use a
forEach
method to loop over the JSON data from the API. - Waiting: 3. Your code should wrap the key names in
strong
tags.
/** * Your test output will go here */