如何使用javascript解析嵌套的jsonp对象?
问题描述:
我有一个有效的jsonp如下。我试图解析它,但我不知道如何访问视频元素!可以在任何一个可以告诉我如何引用里面的那些元素(源,拇指,标题)for循环感谢如何使用javascript解析嵌套的jsonp对象?
有效JSONP:
{
"categories": [{
"name": "october list",
"videos": [{
"sources": [
"http://www.somesite.com.com/test.m3u8"
],
"thumb": "http://www.somesite.com.com/1.jpg",
"title": "title of test",
"subtitle": "",
"description": ""
}, {
"sources": [
"http://www.somesite.com/test2.m3u8"
],
"thumb": "http://www.somesite.com/2.jpg",
"title": "test2",
"subtitle": "",
"description": ""
}
]
}]
}
的javascript:
$.get("http://www.someapisite.com/test.php",
{
dataType: "jsonp"
},
function(data,status){
var json = $.parseJSON(data);
// then loop the single items
for(i in json)
{
// create HTML code
var div = "<div class=\"image\">\n" +
"<a href=\"javascript:dofunction('./test.php?title=" + json[i].title + "&TargetUrl=http://somesite.com/" + json[i].sources + "')\">\n" +
"<img src=\""+ json[i].thumb +"\" alt=\"..\" />\n" +
"</a>\n" +
"</div>\n";
// append it inside <body> tag.
$("#myDiv").append(div);
}
});
答
看来你想要遍历每个类别的视频数组。
使用JavaScript的forEach
json.categories.forEach(function(category, index, array) {
category.videos.forEach(function(videoDetail, index, array) {
<img src=\"" videoDetail.thumb \"" />
<h3>videoDetail.title</h3>
});
});
即*不* JSONP。 – Bergi
您不必调用'$ .parseJSON'。 '$ .ajax' /'$ .get' /'$ .getJSON'已经为你做了这件事(并且在实际的JSONP的情况下,你永远不会看到一个字符串) – Bergi
可能的[Access/process(nested)对象,数组或JSON](http://*.com/q/11922383/1048572)? – Bergi