我在下面的这段代码中不断收到此错误:
function openWebsocket(url) {
var ws;
ws = $websocket(url);
ws.onOpen(function(event) {
console.log(' Websocket connection established:', event);
});
ws.onMessage(function(message) {
var userObj = UserFactory.getUserObject();
var settings = userObj.alert_settings;
// The JSON parsing...
var parsedMsg = JSON.parse(message.data);
var alert = JSON.parse(parsedMsg);
var date = new Date(parseFloat(alert.start_epoch+'000'));
alert.hour = date.getHours() +':'+date.getMinutes();
alert.percent_change = Math.round(alert.percent_change);
var shouldPush = main_alert_filter(settings, alert);
updateFeed(alerts, shouldPush, alert);
});
}
我查看了 Parsing JSON giving “unexpected token o” 错误 并且 我不断收到 “Uncaught SyntaxError: Unexpected token o”
然而,这两个答案都没有帮助。因为当我第一次运行 JSON.parse(message.data) 时,我得到的是一个字符串而不是一个对象。因此,我必须再次运行 JSON.parse 才能最终得到一个真实的对象。
这就是 message.data
的样子:
"
"{\"term\": \"\\\"nike\\\"\", \"percent_change\": 125, \"hour\": \"10:9\", \"term_id\": 2890413, \"start_epoch\": 1420474140, \"term_trend_id\": 793950, \"end_epoch\": 1420477740, \"formatted_date_difference\": \"January 5, 2015\", \"tickers\": [\"NKE\", \"$PUM\", \"ADDYY\", \"LULU\", \"UA\", \"HIBB\"], \"twitter_preview\": \"\", \"type\": \"spike\", \"approved\": 1, \"search_preview\": [\"\"]}"
"
现在在第一次解析之后 parsedMsg
是一个看起来像这样的字符串:
{"term": "minimum wage +increase", "percent_change": 729, "hour": "9:14", "term_id": 2522115, "start_epoch": 1447168440, "term_trend_id": 657898, "end_epoch": 1447175700, "formatted_date_difference": "November 10, 2015", "tickers": ["$JAB", "$SLCY", "AAL", "AAPL", "ABCD", "ABTL", "ADDYY", "ADM", "AEO", "AFCO", "AHC"......
最后我需要一个实际的对象,所以我必须再次运行 JSON.parse 才能得到这个:
Object {term: "minimum wage +increase", percent_change: 729, hour: "9:14", term_id: 2522115, start_epoch: 1447168440…}
另一件需要注意的事情是,当我在 Chrome 中单步执行时,我从来没有遇到过那个错误。只有当我没有设置断点时才会发生。这可能是竞争条件类型的问题吗?就像它尝试 JSON.parse 还没有准备好解析的东西一样?
更新
好的,所以有时 JSON 显然无效,有时无效,到目前为止,我在使用以下代码段时做得很好,没有错误,想法?
if (typeof alert === 'object') {
// do nothing...
} else {
var alert = JSON.parse(alert);
}
大多数时候 alert
结果 JSON.parse(message.data)
是 string
所以我需要其他检查来双重解析它。
原文由 Leon Gaban 发布,翻译遵循 CC BY-SA 4.0 许可协议
您使用
message.data
指定的 JSON 字符串不是解析为字符串的格式正确的 JSON。这可能是因为服务器在建立连接期间/之后向您发送了多部分消息。我建议您打印在
OnMessage
函数中收到的消息对象,并分析它们是否是完全形成的有效 JSON 字符串。