我正在尝试使用 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;
最佳答案
连字符要求您使用括号符号来访问属性 video-title
和 video-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);
}
关于javascript - 通过名称获取 JSON 对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42561288/