简体   繁体   中英

How to parse nested jsonp objects using javascript?

I have a valid jsonp as follows . I am trying to parse it but i don't know how to access videos elements! Could any one tell me how to reference those elements(sources,thumb,title) inside for loop ?Thanks

valid 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);
    }

        });

It seems you want to iterate over the videos array for each category.

Using javascript forEach

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM