-2

I have the json below and I'm trying to traverse to the "results" and get the question value or the incorrect answers values

{
  "response_code": 0,
  "results": [
    {
      "category": "Science & Nature",
      "type": "multiple",
      "difficulty": "medium",
      "question": "Which part of the body does glaucoma affect?",
      "correct_answer": "Eyes",
      "incorrect_answers": [
        "Throat",
        "Stomach",
        "Blood"
      ]
    }
  ]
}

I can get the "response_code", "results" with the code that I wrote below

$(function() {  

    $.getJSON('https://opentdb.com/api.php?amount=10', function(data){
        $.each(data, function(key, val) {
            console.log(key +" or " + val);
        }); 

    });

  });
Andre Silva
  • 23
  • 2
  • 5

2 Answers2

0

You can iterate over the results array with forEach.

$(function () {
  $.getJSON('https://opentdb.com/api.php?amount=10', function (data) {
    data.results.forEach(function (result) {
      var question = result.question;
      var incorrect_answers = result.incorrect_answers;
      console.log(question || incorrect_answers);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rodrigo5244
  • 5,145
  • 2
  • 25
  • 36
-1

You just need to loop through data.results

You should test to make sure it exists first...like I did below

var data = {
  "response_code": 0,
  "results": [
    {
      "category": "Science & Nature",
      "type": "multiple",
      "difficulty": "medium",
      "question": "Which part of the body does glaucoma affect?",
      "correct_answer": "Eyes",
      "incorrect_answers": [
        "Throat",
        "Stomach",
        "Blood"
      ]
    }
  ]
}

if( data.results ){
  
  // jQuery way
  $.each(data.results, function(index, d){
    
    console.log(d.question)
    console.log(d.incorrect_answers)
    
  })
  
  // vanilla JavaScript
  data.results.forEach(function(d, index){
    
    console.log(d.question)
    console.log(d.incorrect_answers)
    
  })
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Kevin Jantzer
  • 9,215
  • 2
  • 28
  • 52