Last active
August 9, 2020 19:41
-
-
Save richleach/408697af7bc83651e3e55fbfc063aef4 to your computer and use it in GitHub Desktop.
fetch a json file, loop through each value in the json file (forEach()) and print it out to a div on screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//FETCH, JSON, FOREACH & DIV.INNERHTML EXAMPLE | |
//fetch a json file, loop through each value in the json file and print it out to a div on screen | |
//this is the contents of the people.json file that would need to be located in the same directory to work on your machine | |
[ | |
{"name": "John", | |
"age": 20}, | |
{"name": "Mary", | |
"age": 24}, | |
{"name": "Bob", | |
"age": 32} | |
] | |
//this is the contents of javascript.js that fetches the json data, loops over the results and prints each value to a div onscreen | |
fetch('people.json') | |
.then( res => res.json() ) //replace 'res.json()' with '{throw 404}' to intentionally throw a 404 error | |
.then( json => { | |
json.forEach( person => { | |
const div = document.createElement('div'); | |
div.innerHTML = `${person.name} is ${person.age} years old.`; | |
document.body.appendChild(div); | |
}) | |
}) | |
.catch(err => console.error(err)); //basic error trapping |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment