如何使用javascript解析嵌套的json对象

How to parse nested jsonp objects using javascript?

本文关键字:json 对象 嵌套 何使用 javascript      更新时间:2023-09-26

我有一个有效的jsonp如下。我试图解析它,但我不知道如何访问视频元素!谁能告诉我如何在for循环中引用这些元素(来源,拇指,标题)?谢谢

有效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);
    }
        });

似乎您想迭代每个类别的视频数组。

json.categories.forEach(function(category, index, array) {
category.videos.forEach(function(videoDetail, index, array) {
    <img src='"" videoDetail.thumb '"" />
    <h3>videoDetail.title</h3>
 });
});