Javascript getJSON如何遍历到子对象

Javascript getJSON如何遍历到子对象,javascript,jquery,json,Javascript,Jquery,Json,我有下面的json,我试图遍历到“结果”,并得到问题值或错误答案值 我可以用我在下面写的代码得到“response_code”、“results” $(function() { $.getJSON('https://opentdb.com/api.php?amount=10', function(data){ $.each(data, function(key, val) { console.log(key +" or " + val);

我有下面的json,我试图遍历到“结果”,并得到问题值或错误答案值

我可以用我在下面写的代码得到“response_code”、“results”

$(function() {  

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

    });

  });
您只需循环查看
数据。结果
您应该首先测试以确保它存在……就像下面我所做的那样

var数据={
“响应代码”:0,
“结果”:[
{
“类别”:“科学与自然”,
“类型”:“多个”,
“难度”:“中等”,
“问题”:“青光眼影响身体的哪个部位?”,
“正确答案”:“眼睛”,
“回答不正确”:[
“喉咙”,
“胃”,
“血”
]
}
]
}
if(data.results){
//jQuery方式
$.each(数据、结果、函数(索引、d){
console.log(d.question)
console.log(d.回答不正确)
})
//香草JavaScript
data.results.forEach(函数(d,索引){
console.log(d.question)
console.log(d.回答不正确)
})
}

您可以使用遍历结果数组

$(函数(){
$.getJSON('https://opentdb.com/api.php?amount=10,函数(数据){
data.results.forEach(函数(结果){
var问题=结果问题;
var错误答案=结果。错误答案;
console.log(问题| |回答不正确);
});
});
});

$。每个(数据、结果、函数(键、值)我必须将其更改为data.results.forEach吗,我不能使用$。getJSON的每个方法吗?你仍然可以使用jQuery
$。每个
。我刚刚演示了如何不用jQuery。我如何使用键值?只是为了深入了解孩子们为什么会投反对票?不是我,我讨厌他们那样做
$(function() {  

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

    });

  });