【发布时间】:2020-11-05 20:49:31
【问题描述】:
我正在尝试从服务器获取数据并对其进行解析,以便将其格式化为以 HTML 显示的内容
我在解析 JSON 文件中的数据时遇到问题
这是我的代码:
JS
var AnnouncementsJSON
$.get("data/announcements.json", function(data) {
console.log(data)
AnnouncementsJSON = $.parseJSON(data)
});
console.log(AnnouncementsJSON)
announcements.json
{
"announcements":[
{
"title":"This is the Announcement!",
"subtitle":"This is going to be used as announcements",
"link":"/somewhere.html"
}
]
}
控制台/检查元素:
(index):189 {announcements: Array(1)}
VM976:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
at Function.parse [as parseJSON] (<anonymous>)
at Object.success ((index):190)
at c (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at l (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
(anonymous) @ (index):190
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
l @ jquery.min.js:2
(anonymous) @ jquery.min.js:2
load (async)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
S.<computed> @ jquery.min.js:2
(anonymous) @ (index):188
错误消息上方显示{Announcements: Array(1)},所以我知道我可以从浏览器访问 JSON 文件。另外,我导航到它并且能够访问它
【问题讨论】:
-
“Unexpected token o”几乎总是意味着你根本没有得到 JSON:打开你的开发工具,选择网络选项卡,重新运行你的 fetch 并查看你的'正在实际上回来。
-
"Unexpected token o" 通常在您尝试解析已经解析过的内容时出现。记录
typeof data,如果是“对象”,jQuery 已经为你解析好了。
标签: javascript jquery json ajax