getJSON每个如何遍历子对象

时间:2017-02-07 22:26:30

标签: javascript jquery json

我有下面的json,我试图遍历"结果"并且获取问题值或错误的答案值

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

我可以获得" response_code","结果"使用我在下面写的代码

$(function() {  

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

    });

  });

2 个答案:

答案 0 :(得分:0)

您可以使用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>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

您只需要遍历data.results

你应该测试以确保它首先存在...就像我在下面做的那样

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>