以下是我的PHP脚本回显的JSON片段:
[
{
"title": "4th of July",
"start": "2014-07-04"
},
{
"title": "5th of May",
"start": "2014-05-05"
},
{
"title": "My Birthday",
"start": "2014-02-03"
}
]
我试图遍历所有事件并将其列出。 我遇到的问题是进入数据的更深层次。有人能帮助我吗?
如果我要更深入地添加数组呢?像这样:
[
{
"title": "4th of July",
"start": "2014-07-04",
"activities": [
"badmitten",
"tennis"
]
}
]
这是我尝试过的:
$.getJSON("json.json", function(data) {
var items = [];
$.each(data, function(key, val) {
//items.push("<li id='" + key + "'>" + val + "</li>");
});
$.each(data, function(obj) {
$.each(obj, function(key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
});
});
});
答案 0 :(得分:1)
尝试:
var data = [
{
"title": "4th of July",
"start": "2014-07-04"
},
{
"title": "5th of May",
"start": "2014-05-05"
},
{
"title": "My Birthday",
"start": "2014-02-03"
}
]
data.forEach(function(d){
// do whatever to each of the item in the array
console.log(d.title);
console.log(d.start);
});
对于更深层次的数据,只需使用相同的方式向下钻取。在上面的循环中:
if(d.activities && d.activites.length > 0){
d.activities.forEach(function(a){
console.log(a);
})
}
希望有所帮助
答案 1 :(得分:0)
有点晚了,因为你已经接受了答案,但如果你想要它是动态的,你可以设置一个递归函数,如下所示:
function printSection(obj) {
var items = ['<ul>'];
$.each(obj, function(key, value) {
var item = '<li'+ (isNaN(key) ? ' id="'+ key +'"' : '') +'>';
if (value instanceof Object) {
item += key +':';
item += printSection(value);
} else {
item += value;
}
item += '</li>';
items.push(item);
});
items.push('</ul>');
return items.join('');
}
这样,您可以添加更多级别的嵌套,而无需更改输出循环。
$.getJSON('json.json', function(data) {
var result = [];
$.each(data, function() {
result.push(printSection(this));
});
$('#result').html(result.join(''));
}