按名称获取JSON对象的属性

时间:2017-03-02 16:52:06

标签: javascript json

我正在尝试使用JSON来保存有关一组视频的信息。我已成功读取JSON文件,但在尝试访问该对象的属性时遇到了一些困难。当我尝试访问数组“fastvideos”时,虽然数组作为对象加载,但obj.fastvideos[x]仍未定义。

这是我的JSON问题,还是我试图访问该对象的问题?

JSON

{
"fastvideos": [{
    "video-title": "sampletitle",
    "video-tags": "tag1, tag2, tag3",
    "video-desc": "sample-desc",
    "video-url": "https://www.youtube.com/watch?v=<redacted>"
    }, {
    "video-title": "sampletitle2",
    "video-tags": "tag1, tag2, tag3",
    "video-desc": "sample-desc-2",
    "video-url": "https://www.youtube.com/watch?v=<redacted>"
    }]
}

JS

var obj = $.getJSON("videolist.json", function(json){
console.log(json);
});

document.getElementById("demo").innerHTML =
obj.fastvideos[1].video-title + ": URL =  " + obj.fastvideos[1].video-url;

2 个答案:

答案 0 :(得分:4)

连字符要求您使用括号表示法来访问属性video-titlevideo-url

此外,对getJSON的调用不会返回JavaScript对象,而是返回对jqXHR对象的引用。您实际上不需要在您的情况下使用该对象,因为您有一个正在侦听成功回调的函数。该函数的参数将包含已解析的JavaScript对象。

$.getJSON("videolist.json", function(obj){
    document.getElementById("demo").innerHTML =
    obj.fastvideos[1]["video-title"] + ": URL =  " + obj.fastvideos[1]["video-url"];
});

如何迭代视频:

var obj = 
{
"fastvideos": [{
    "video-title": "sampletitle",
    "video-tags": "tag1, tag2, tag3",
    "video-desc": "sample-desc",
    "video-url": "https://www.youtube.com/watch?v=<redacted>"
    }, {
    "video-title": "sampletitle2",
    "video-tags": "tag1, tag2, tag3",
    "video-desc": "sample-desc-2",
    "video-url": "https://www.youtube.com/watch?v=<redacted>"
    }]
};

for (var i = 0; i < obj.fastvideos.length; i++) {
    var video = obj.fastvideos[i];
    var title = video["video-title"];
    var tags =  video["video-tags"];
    var desc =  video["video-desc"];
    var url =  video["video-url"];
    
    console.log(i + " : " + title + " : " + tags + " : " + desc + " : " + url);
}

答案 1 :(得分:0)

试试这个

var tArray = {
"fastvideos":
    [   {
            "video-title": "sampletitle",
            "video-tags": "tag1, tag2, tag3",
            "video-desc": "sample-desc",
            "video-url": "https://www.youtube.com/watch?v=<redacted>"
        }, 
        {
            "video-title": "sampletitle2",
            "video-tags": "tag1, tag2, tag3",
            "video-desc": "sample-desc-2",
            "video-url": "https://www.youtube.com/watch?v=<redacted>"
        }
    ]
};


alert(tArray["fastvideos"][0]["video-title"])

for(var i=0; i<tArray["fastvideos"].length; i++){
    alert( tArray["fastvideos"][i]["video-title"] );
}

https://jsfiddle.net/gj1u6rpm/1/