Home > database >  HTML element from json file
HTML element from json file

Time:12-28

I have a json file that looks like this:

{ "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" } } }

I have to get elements from it and return html element with it. I tried this but it didn't work.

 let promise = fetch('quiz.json').then(function (response) {
        if (!response.ok) {
            throw Error("Error while reading this file.");
        }

        return response.json();
    }).then(function (data) {
       for (let i = 0; i < data.length; i  ) {
            document.body.innerHTML  = '<h2>'   data[i].question   '</h2>'
            document.body.innerHTML  = '<input type="radio">'   data[i].options  
        }            

        console.log(data);

    }).catch(function (err) {
        console.log('Error: '   err.message);
    });

CodePudding user response:

Json file look like this.{ "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" } } }

CodePudding user response:

for (let que in data.quiz) {
   document.body.innerHTML  = '<h2>'   que.question   '</h2>';
   for (let i = 0; i < que.options.length; i  ) {
     document.body.innerHTML  = '<input type="radio">'   que.options[i];
   }
}

Correct the loop.

  • Related