0

So im having issues here, when I do a console check I can get my json file to print out its conent into the console using console.log but now im trying to print this out on the page.

I want to print out the first one called information inside the json out to the screen using innerHTML so it basically looks like this:

enter image description here

The second part need to make the one called websites print out as ul.

This is my js so far:

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 just cant seem to reach the object I want and print it out.

This is my json code:

{
    "Student": [
        {
            "Information": 
                {
                    "Namn" : "Emil",
                    "Email" : "emilpalm94@gmail.com",
                    "City" : "Linköping",
                    "Website" : "http://studenter.miun.se/~empa1600/"
                }

        },
        {
            "Websites": [
                {
                    "Sitename" : "komplett",
                    "SiteURL" : "https://www.komplett.se/",
                    "Description" : "Bra sida för köp av teknik"
                },
                {
                    "Sitename": "Inet",
                    "SiteURL": "https://www.inet.se/",
                    "Description": "Konkurerande sida mot Komplett"
                },
                {
                    "Sitename": "SF",
                    "SiteURL": "https://www.sf.se/",
                    "Description": "När man ska se bio med polaren"
                },
                {
                    "Sitename": "Code Academy",
                    "SiteURL": "https://www.codecademy.com/",
                    "Description": "Lär dig koda"
                },
                {
                    "Sitename": "Miun",
                    "SiteURL": "https://www.miun.se/",
                    "Description": "Här lär vi oss allt"
                }
            ]
        }
    ]
}

I want the first section to print out

Anaother pic of my current look of the site: https://gyazo.com/ef4b02c9474f443747df6fcdaf5537b6

I did manage once to print out with innerHTML but it just said undefined which I dont get why.

How can I get the section called Information to print out like the first pic and then the websites to list in a Li element?

Thanks!

Edit: How can I now get the json array websites to print out? and be like the picture? also so they are clickable links?

This is what I tried so far:

function printOut(){
        jsonStr.Student[1].Websites.forEach(w => {
            document.getElementById("sites").innerHTML += w.Sitename + "<br>";
        });

    }
    printOut();
Palmolito
  • 9
  • 4
  • Do you have any control over the JSON structure? The `Student` array seems unnecessary, it would be better for it to be an object with `Information` and `Websites` properties. – Barmar Sep 18 '18 at 09:22
  • I do yes, but for this task this is exactly how it needs to be, maybe not most effective but its like that for this task – Palmolito Sep 18 '18 at 09:34

3 Answers3

0

Try this instead :

var xhr = new XMLHttpRequest();

xhr.onreadystatechange= function() {
if(xhr.readyState == 4 && 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);
  • Don't just post code. Explain what's wrong in his code, and how you fixed it. – Barmar Sep 18 '18 at 09:12
  • This code won't work. It's not accessing the JSON data correctly. See my answer. `onload` is perfectly fine for handling when the AJAX response is received. – Barmar Sep 18 '18 at 10:28
0

You have no variable Student in your code. Student is a property in the object returned from JSON.parse() which is in the jsonStr variable. So

Also, the Namn property is within the Information property, you can't skip that.

So Student[0].Namn should be jsonStr.Student[0].Information.Namn.

See Access / process (nested) objects, arrays or JSON for more information on this topic.

To access the Website data, it's similar. Since it contains an array you can loop over it.

var l = "<ul>";
jsonStr.Student[1].Websites.forEach(w => {
    l += `<li><a href="${w.SiteURL}">${w.Description}</a></li>`;
});
l += "</ul>";
document.getElementById("sites").innerHTML = l;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • thanks that fixed it! The jsonStr. made it work, if I now in the second part want to list the websites, do I use a for loop or something? Thanks for solving the first issue! – Palmolito Sep 18 '18 at 09:19
  • Yes. `Student[0].Websites.forEach(website => { //code })` – Barmar Sep 18 '18 at 09:21
  • You can use for in loop to iterate through object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in and forEach - to iterate through array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – Vadi Sep 18 '18 at 09:22
  • @Vadi Websites is an array, not an object. – Barmar Sep 18 '18 at 09:23
  • @Palmolito Oops, that should be `jsonStr.Student[1].Websites.foreach`. That's why this is a poor design, you shouldn't have to hard-code array indexes like this. Arrays should be used for uniform data, objects should be for heterogeneous data. – Barmar Sep 18 '18 at 09:40
  • @Barmar thanks for all the help so far, could u maybe show example of the for loop if u dont mind? – Palmolito Sep 18 '18 at 09:42
  • @Palmolito I added it, but if you know how to loop over arrays in general, this should be no different. – Barmar Sep 18 '18 at 09:44
  • Ok thanks, one more question, I need to turn these websites into links, how do i get around to doing that? for the top part of the pic i made variables that works but it seems there have to be a better way – Palmolito Sep 18 '18 at 09:49
  • It sounds like you need to read a good jQuery tutorial to learn how to use it to create DOM elements. – Barmar Sep 18 '18 at 09:52
  • we cant use jquery for this task at all sadly – Palmolito Sep 18 '18 at 09:53
  • Oops, didn't notice that. So just create the HTML as strings. `div.innerHTML += \`${w.Description}\`;` – Barmar Sep 18 '18 at 09:56
  • Sorry I will comment here now in ur answer, I changed the foreach to forEach, still nothing showing up hmm – Palmolito Sep 18 '18 at 10:29
  • You need to pass `jsonStr` as an argument to `printOut`. You need to learn about variable scope. – Barmar Sep 18 '18 at 10:30
  • Ok so I fixed it to print out now, the code in the question bottom of page now updated, what do I need to add to make these into links? also can i make them into a unordered list to get a bullet infront of them? – Palmolito Sep 18 '18 at 10:31
  • You an do whatever you want. You're constructing strings of HTML, just put all the markup in there. Like the example in my earlier comment. – Barmar Sep 18 '18 at 10:33
  • I'm not going to spend all day teaching you how to create HTML in JavaScript. – Barmar Sep 18 '18 at 10:34
  • BTW, it's generally best to create all the HTML in a string during the loop, then assign it at once to `innerHTML` when the loop is done. – Barmar Sep 18 '18 at 10:35
  • Sry for all the questions, but one FINAL one, I fixed so there are bullets, but how do I make it so each of the sites link to the page? because the other ones I hardcoded a variable but Im not sure how to make the code so I get them to link – Palmolito Sep 18 '18 at 10:35
  • I've updated my answer to show how to create the bullets and links. – Barmar Sep 18 '18 at 10:37
  • I solved it, thanks to you, thank you so so so much man! Your a true expert! ;) – Palmolito Sep 18 '18 at 10:40
-1

As an explanation to the previous code I wrote,I think replacing onload with onreadystatechange and replacing your if statement with if(xhr.readyState == 4 && xhr.status == 200) which checks whether ajax message is sent accurately or not would be the solution.