Lesson 1: Loading JSON Data
Fetching Data from the JSON File
We will use JavaScript to load the JSON file and display the country-specific answers. For this we're going to again create a new file in our folder called script.js and we're going to be copying two bits of code that were generated by ChatGPT.
Essentially, the first bit of code fetches the json data. The second one populates the drop down menu with the countries and populates the rest of the page with the flag and the answer to our question, which you might remember in my example was a brief history of each country. Once we have these pieces of code in place and saved in the folder, we are ready for the next stage. Happy pasting!
JavaScript Code for Fetching the JSON
document.addEventListener("DOMContentLoaded", function() {
fetch("country_data.json")
.then(response => response.json())
.then(data => {
populateDropdown(data);
})
.catch(error => console.error("Error loading JSON:", error));
});
function populateDropdown(data) {
const dropdown = document.getElementById("countryDropdown");
data.forEach(country => {
let option = document.createElement("option");
option.value = country.name;
option.textContent = country.name;
dropdown.appendChild(option);
});
}
JavaScript Code for Displaying Data
document.getElementById("countryDropdown").addEventListener("change", function() {
let selectedCountry = this.value;
fetch("country_data.json")
.then(response => response.json())
.then(data => {
let countryInfo = data.find(country => country.name === selectedCountry);
if (countryInfo) {
document.getElementById("countryName").textContent = countryInfo.name;
document.getElementById("countryFlag").src = countryInfo.flag;
document.getElementById("countryAnswer").textContent = countryInfo.answer;
document.getElementById("infoContainer").style.display = "block";
}
})
.catch(error => console.error("Error fetching country data:", error));
});
Now we need to upload our files to the Internet to see our masterpiece.