JSON.parse 导致“未捕获的语法错误:意外的令牌 u”

JSON.parse causes "Uncaught SyntaxError: Unexpected token u"

本文关键字:错误 意外 令牌 语法 JSON 导致 parse      更新时间:2023-09-26

我有:

<input type="hidden" id="notifications" value="@ViewBag.Notifications" />

当我在此行上放置断点并检查值时,我看到该值为:

[{"id":"42647","isRead":0,"MessageType":3},{"id":"fsh3hg","isRead":0,"MessageType":2}]

我想在页面加载时在 JavaScript 中解析这个值,所以我写了:

var notifications = document.getElementById('notifications').value;
alert(notifications); // it prints undefined
alert(document.getElementById('notifications')); // it prints: Object HtmlSpanElement
var parsedNotifications;
if (notifications != '') {
    parsedNotifications = JSON.parse(notifications);
}

但我在以下行收到错误"未捕获的语法错误:意外的令牌u":

parsedNotifications = JSON.parse(notifications);

为什么会发生此错误?

你写道:

alert(document.getElementById('notifications')); // it prints: Object HtmlSpanElement

在评论中,HtmlSpanElement是出现问题的线索。显然,您的页面有一个<span>,其id与隐藏<input>相同,因此document.getElementById找到错误的元素,并且value返回undefined,因为<span>没有值。

<span> id更改为"通知"以外的内容,您的代码应该可以工作。

所以我们知道document.getElementById('notifications'(在那里,这意味着唯一的问题是它找不到输入值。 有时外部库会阻止隐藏元素的输入。 剥离您的页面中除您向我们展示的代码之外的所有内容,然后尝试逐个添加您包含的其他库,直到找到问题所在。