我试图通过api遍历json中返回的所有对象。这是我的代码:
$(document).ready(function() {
$('.form-container').submit(function() {
var $body = $('body');
var $greeting = $('#greeting');
// load streetview
var streetname = $("#street").val();
var cityname = $("#city").val();
var address = streetname + ', ' + cityname;
var bigImgUrl = "https://maps.googleapis.com/maps/api/streetview?size=600x400&location="+ address +'';
$greeting.text("So you want to live at " + address + "?");
$body.append('<img class="bgimg" src='+bigImgUrl+'>');
// NYTimes AJAX request
var nytUrl = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q="+cityname+"&sort=newest&api-key=####";
$.getJSON(nytUrl, function(data) {
createStructure(data); // Call to recursive function
});
return false;
});
var createStructure = function (data)
{
$.each(data, function(key, value) {
if (typeof value === 'object')
{
alert(key + ": " + value);
createStructure(data[key]);
}
else
{
alert(key + ": " + value);
}
});
};
return false;
});
然而,它并没有遍历所有这些。这是一个屏幕截图,描述了API返回的部分json:
代码会显示仅输入response
,所有meta
(包括子项),提交docs
和0
对象(仅限某些子元素)的提醒。
它会跳过docs
的所有剩余子项和其他外部对象。
以下是json的链接:JSON
答案 0 :(得分:1)
使用for
in
循环代替$.each
:
var createStructure = function (data) {
for (var key in data){
var value = data[key];
if (typeof value === 'object') {
console.log(key + ": " + value);
createStructure(value);
} else {
console.log(key + ": " + value);
}
}
};