Lazar Mladenovic
Lazar Mladenovic

Reputation: 1

Turning JSON file into HTML radio quiz

I need to fetch JSON file, sort it's Question,Possible aswers and then display correct answer but I cant fetch and sort it properly

    <script>
            fetch("quiz.json").then(function (response) {

                response.json()

            }).then(function(quiz){
                for(let i = 0; 1 <quiz.length; i++){
                    document.body.innerHTML += '<h2>' +quiz[i].question + '</h2>';
                    document.body.innerHTML += '<imput type="radio">' +quiz[i].options ;
                    document.body.innerHTML += '<p>' +quiz[i].answer + '</p>';
                }
            })
    </script>

When I try it it says "

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length')
    at (index):30:40
```"

JSON file : 

{ "quiz": { "q1": { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" }, "q2": { "question": "'Namaste' is a traditional greeting in which Asian language?", "options": [ "Hindi", "Mandarin", "Nepalese", "Thai" ], "answer": "Hindi" }, "q3": { "question": "The Spree river flows through which major European capital city?", "options": [ "Berlin", "Paris", "Rome", "London" ], "answer": "Berlin" }, "q4": { "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": [ "Pablo Picasso", "Vincent van Gogh", "Salvador Dalí", "Edgar Degas" ], "answer": "Pablo Picasso" } } }


Also Im using XAMPP and only vanilla js

Upvotes: 0

Views: 71

Answers (1)

Speed
Speed

Reputation: 33

Try changing your data to

{ "quiz": [
        { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" },
        
        { "question": "'Namaste' is a traditional greeting in which Asian language?", "options": [ "Hindi", "Mandarin", "Nepalese", "Thai" ], "answer": "Hindi" }, 
        
        { "question": "The Spree river flows through which major European capital city?", "options": [ "Berlin", "Paris", "Rome", "London" ], "answer": "Berlin" }, 
        
        { "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": [ "Pablo Picasso", "Vincent van Gogh", "Salvador Dalí", "Edgar Degas" ], "answer": "Pablo Picasso" } 
    ] 
}

that will make quiz an array, and then you can navigate it with your code.

Upvotes: 0

Related Questions