Javascript JSON 中位置 1 的意外标记 o

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38576691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:36:49  来源:igfitidea点击:

Unexpected token o in JSON at position 1

javascriptjsonparsing

提问by Leon Gaban

I keep getting this error in this block of code below:

我在下面的代码块中不断收到此错误:

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);
    });
}

I've looked at both Parsing JSON giving "unexpected token o" errorand I keep getting "Uncaught SyntaxError: Unexpected token o"

我已经查看了解析 JSON 给出“意外的令牌 o”错误,但我不断收到“未捕获的语法错误:意外的令牌 o”

However neither answer helped. Because when I first run JSON.parse(message.data) I get a string back not an Object. So thus I have to run JSON.parse again to finally get a real object back.

然而,这两个答案都没有帮助。因为当我第一次运行 JSON.parse(message.data) 我得到一个字符串而不是一个对象。因此,我必须再次运行 JSON.parse 才能最终获得一个真实的对象。

enter image description here

在此处输入图片说明

This is what message.datalooks like:

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\": [\"\"]}" "

" "{\"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\": [\"\"]}" "

Now after the first parsing parsedMsgis a string that looks like this:

现在在第一次解析之后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"......

{"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"......

Finally I need an actual object, so I have to run JSON.parse again to get this:

最后我需要一个实际的对象,所以我必须再次运行 JSON.parse 来得到这个:

Object {term: "minimum wage +increase", percent_change: 729, hour: "9:14", term_id: 2522115, start_epoch: 1447168440…}

Object {term: "minimum wage +increase", percent_change: 729, hour: "9:14", term_id: 2522115, start_epoch: 1447168440…}

Another thing to note, I never get that error when I'm stepping through in Chrome. It only happens when I don't have the breakpoint set. Could this be a race condition type issue? Like it tries to JSON.parse something that isn't ready to be parsed?

另一件要注意的事情是,当我在 Chrome 中逐步执行时,我从未遇到过该错误。只有当我没有设置断点时才会发生这种情况。这可能是竞争条件类型的问题吗?就像它试图 JSON.parse 一些尚未准备好被解析的东西一样?



UPDATE

更新

Ok so sometimes the JSON is invalid apparently and sometimes not, so far I'm doing good without errors with the following snippet, thoughts?

好的,所以有时 JSON 显然无效,有时则无效,到目前为止,我在以下代码段中做得很好,没有错误,想法?

if (typeof alert === 'object') {
    // do nothing...
} else {
    var alert = JSON.parse(alert);
}

Most of the time the alertresult of JSON.parse(message.data)is a stringso I need the other check to double parse it.

大多数时候的alert结果JSON.parse(message.data)是 astring所以我需要另一个检查来双重解析它。

采纳答案by Surya

The JSON string you specified with message.datais not a well formed JSON parsed as String. It might be because the server is sending you a multi-part message during/after establishing the connection.

您指定的 JSON 字符串message.data不是解析为字符串的格式正确的 JSON。这可能是因为服务器在建立连接期间/之后向您发送了多部分消息。

I suggest you print the message object received in OnMessagefunction and analyze if they are fully formed valid JSON Strings.

我建议您打印在OnMessage函数中接收到的消息对象并分析它们是否是完全形成的有效 JSON 字符串。

回答by M.Tanzil

Why would you parseyour json second time, its already been parsed in the first attempt.

你为什么要parse第二次使用你的 json,它已经在第一次尝试中被解析了。

Have a look at the snippet

看一下片段

var obj = "{\"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\"]}";
$(function(){
  var data = JSON.parse(obj);
  alert(typeof data);
  console.log(data.tickers[0] +" -> an item in `tickers` array");
  console.log(data.tickers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

回答by rtbm

It looks like Your message.datais incomplete.

看起来您的message.data不完整。

Take a look on the library docs You are using, maybe you should collect the data until it's end? Maybe there is some onEnd method?

看看你正在使用的图书馆文档,也许你应该收集数据直到它结束?也许有一些 onEnd 方法?