Having some trouble here. I can successfully print my JSON file content to the console using console.log, but now I'm trying to display it on the page.
I want to display the 'Information' section from the JSON file using innerHTML like this:
https://i.sstatic.net/TFX6V.png
The second part should display the 'Websites' section as a list.
This is my current JavaScript code:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
console.log(xhr.responseText);
var jsonStr = JSON.parse(xhr.responseText);
document.getElementById("info").innerHTML += Student[0].Namn + ", ";
}
};
xhr.open("GET", "student.json", true);
xhr.send(null);
I'm having trouble accessing and displaying the specific object I need.
This is my JSON data:
{
"Student": [
{
"Information":
{
"Namn" : "Emil",
"Email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2979f9b9e82993e99999cbbb2999f939b9ecdc09d9c">[email protected]</a>",
"City" : "Linköping",
"Website" : "http://studenter.miun.se/~empa1600/"
}
},
{
"Websites": [
{
"Sitename" : "komplett",
"SiteURL" : "https://www.komplett.se/",
"Description" : "Great site for tech purchases"
},
{
"Sitename": "Inet",
"SiteURL": "https://www.inet.se/",
"Description": "Competing site against Komplett"
},
{
"Sitename": "SF",
"SiteURL": "https://www.sf.se/",
"Description": "When you're going to the movies with your friend"
},
{
"Sitename": "Code Academy",
"SiteURL": "https://www.codecademy.com/",
"Description": "Learn how to code"
},
{
"Sitename": "Miun",
"SiteURL": "https://www.miun.se/",
"Description": "Where we learn everything"
}
]
}
]
}
I want the first section to be displayed
Another screenshot of my current website: https://gyazo.com/ef4b02c9474f443747df6fcdaf5537b6
I once managed to display using innerHTML but it just showed undefined, which I don't understand.
How can I display the 'Information' section like the first image and then list the websites in a <li> element?
Thanks!
Edit: How do I now display and style the 'Websites' array from the JSON data? And have them as clickable links?
This is what I've tried:
function printOut(){
jsonStr.Student[1].Websites.forEach(w => {
document.getElementById("sites").innerHTML += w.Sitename + "<br>";
});
}
printOut();