我有一个JSON Feed,我正在使用它包含attributes
的一个实例和posts
内的许多对象。
我有一个javascript算法,我正在处理JSON数据,我的attributes
值很好(它们充当设置),但我无法处理posts
正常。
JSON响应
[
{
"attributes":{
"dfp_pos":"3",
"dfp_shortcode":"[dfp_ads id=1383]",
"wildcard_pos":"5",
"wildcard_shortcode":"[widget id=\"wp_widget-46\"]",
"twitter_id":"@ScreenName",
"twitter_pos":"8",
"facebook_id":"screenName",
"facebook_pos":"10"
},
"posts":[
{
"id":3945,
"pub_date":"2016-05-30 00:00:00",
"title":"Post title 1",
"excerpt":""
},
{
"id":3574,
"pub_date":"2016-05-12 00:00:00",
"title":"Post Title 2",
"excerpt":""
},
{
"id":3048,
"pub_date":"2016-05-07 00:00:00",
"title":"Post Title 3",
"excerpt":""
}
]
]
的Javascript
var dfp_pos = feeds[0].attributes.dfp_pos;
var dfp_shortcode = feeds[0].attributes.dfp_shortcode;
var wildcard_pos = feeds[0].attributes.wildcard_pos;
var wildcard_shortcode = feeds[0].attributes.wildcard_shortcode;
var twitter_id = feeds[0].attributes.twitter_id;
var twitter_pos = feeds[0].attributes.twitter_pos;
var facebook_id = feeds[0].attributes.facebook_id;
var facebook_pos = feeds[0].attributes.facebook_pos;
jQuery.each(feeds.posts, function(i, post) {
var id = post.id;
var pub_date = post.pub_date;
var title = post.title;
var excerpt = post.excerpt;
console.log(id);
console.log(pub_date);
console.log(title);
console.log(excerpt);
});
each
循环似乎没有通过JSON数据?
答案 0 :(得分:2)
你忘了一层:
data = [
^ {
| ^ "attributes":{
| | "posts":[
| | ^
1 2 3
给你:
data[0].posts
^ ^ ^
1 2 3
答案 1 :(得分:0)
您必须遍历Feed [0]
var dfp_pos = feeds[0].attributes.dfp_pos;
var dfp_shortcode = feeds[0].attributes.dfp_shortcode;
var wildcard_pos = feeds[0].attributes.wildcard_pos;
var wildcard_shortcode = feeds[0].attributes.wildcard_shortcode;
var twitter_id = feeds[0].attributes.twitter_id;
var twitter_pos = feeds[0].attributes.twitter_pos;
var facebook_id = feeds[0].attributes.facebook_id;
var facebook_pos = feeds[0].attributes.facebook_pos;
jQuery.each(feeds[0].posts, function(i, post) {
var id = post.id;
var pub_date = post.pub_date;
var title = post.title;
var excerpt = post.excerpt;
console.log(id);
console.log(pub_date);
console.log(title);
console.log(excerpt);
});