我在函数中有以下代码来读取 JSON 文件:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = this.responseText;
console.log(myObj);
JSON.parse(myObj); // error is here
}
};
xmlhttp.open("GET", "music-data.json", true);
xmlhttp.send();
JSON 数据来自与我的 html/css/js 文件相同的本地文件夹,其结构如下:
window.MUSIC_DATA = {
"list1": [
{
data here...
},
],
"list2": [
{ data here...
...
}
我无法解析我的对象并从 list1 和 list2 中提取我需要的内容,并在现有代码中出现错误:
Uncaught SyntaxError: Unexpected token w in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xmlhttp.onreadystatechange
最佳答案
问题在于
window.MUSIC_DATA =
这不是 JSON,而是 JavaScript。从文件中删除它,以便只留下该值,并且它可能会起作用(或者该文件可能存在其他问题)。
关于javascript - 将 JSON 数据读入 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41714619/