JSON解析意外的非空白字符(JSON parse unexpected non

编程入门 行业动态 更新时间:2024-10-12 08:23:49
JSON解析意外的非空白字符(JSON parse unexpected non-whitespace character)

目前得到以下变量

“{”错误“:”错误的帐户“}”

我解析它就像这样

var message = JSON.parse(event.data); console.log(message['error'])

console.log工作但我得到这个错误

SyntaxError:JSON.parse:JSON数据的第1行第1列的意外字符

我认为json格式是正确的(使用php json_encode制作)所以我真的不知道这个错误

Currently got the following variable

"{"error":"Wrong account"}"

And Im parsing it like this

var message = JSON.parse(event.data); console.log(message['error'])

The console.log works but Im getting this error

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I think the json format is correct (made using php json_encode) so I dont really know wheres the error

最满意答案

因此,经过一些调试(参见下面的反向链接),事实证明问题是另一条非JSON编码的消息首先被相关代码捕获。

虽然我们可以追溯到其他消息来自哪里(在进一步的讨论中,显然有一个握手是在同一个套接字上发送并被这个处理程序拾取 - 最后的罪魁祸首!),它可能更容易只是放弃它,所以我们需要一些验证码:

归功于@Gumbo和@Matt对以下内容的答案的混合 (因为我们需要实际运行测试,但是也想检查null / etc的情况,所以当我们去参考返回时我们不会抛出错误目的)

function IsValidJSON(test) { try { var obj = JSON.parse(test); if (obj && typeof obj === "object" && obj !== null) { return true; } } catch (e) { } return false; }

有了这个功能,现在我们可以简单地将原始代码更改为:

var message; if (IsValidJSON(event.data)) { message = JSON.parse(event.data); console.log(message['error']); }

我将以下早期版本的答案留作调试跟踪,因为这最终成为一个发现问题的过程,而不是问题和解决方案不言自明的过程:


所以这已经变得有点神秘了,让我们尝试回归基础并验证输出中没有任何奇怪/不可打印的东西:

var asciioutput = event.data.charAt(0) + ':' + event.data.charCodeAt(0); for (var i = 1; i < event.data.length; i++) { asciioutput += ', ' + event.data.charAt(i) + ':' + event.data.charCodeAt(i); } console.log(asciioutput);

您最终应该在控制台中得到如下结果:

{:123, ":34, e:101, r:114, r:114, o:111, r:114, ":34, ::58, ":34, W:87, r:114, o:111, n:110, g:103, :32, a:97, c:99, c:99, o:111, u:117, n:110, t:116, ":34, }:125

如果您的变量包含那些包装引号,那么它们就是问题:删除它们。

换句话说,如果console.log(event.data)显示,字面意思是"{"error":"Wrong account"}"那么您需要剥离包装引号,使变量变为{"error":"Wrong account"}在尝试将其解析为JSON之前。

例如:

var message; if (event.data.slice(0,1) == '"') { message = JSON.parse(event.data.slice(1,-1)); } else { message = JSON.parse(event.data); }

(有关工作示例,请参阅jsfiddle - 注意名称更改)

(请注意,此示例完全假定如果有一个起始引用,则还有一个结束引用:如果不一致,您可能需要构建更多逻辑)

So after some debugging (see below in reverse for that chain) it turns out the issue is another message which isn't JSON encoded is being caught by the related code first.

While we could trace through to where the other message is coming from (on further discussion, there is apparently a handshake that was being sent on the same socket and getting picked up by this handler—the culprit at last!), it might be easier to just drop it, so we need some validation code:

Credit to an amalgam of the answers by @Gumbo and @Matt for the following (because we need to actually run a test, but want to check for null/etc cases too so we're not throwing errors when we go to reference the return object)

function IsValidJSON(test) { try { var obj = JSON.parse(test); if (obj && typeof obj === "object" && obj !== null) { return true; } } catch (e) { } return false; }

With that function available, now we can simply change the original code to:

var message; if (IsValidJSON(event.data)) { message = JSON.parse(event.data); console.log(message['error']); }

I'm leaving the following earlier versions of the answer in as a debug trail, since this ended up being more of a process of finding the problem than one where the problem and solution were self evident:


So this has turned slightly mysterious, let's try going back to basics and verifying that nothing weird/unprintable is in the output:

var asciioutput = event.data.charAt(0) + ':' + event.data.charCodeAt(0); for (var i = 1; i < event.data.length; i++) { asciioutput += ', ' + event.data.charAt(i) + ':' + event.data.charCodeAt(i); } console.log(asciioutput);

You should end up with a result in your console that looks like this:

{:123, ":34, e:101, r:114, r:114, o:111, r:114, ":34, ::58, ":34, W:87, r:114, o:111, n:110, g:103, :32, a:97, c:99, c:99, o:111, u:117, n:110, t:116, ":34, }:125

If your variable includes those wrapping quotes, then they are the problem: remove them.

In other words, if console.log(event.data) shows, literally "{"error":"Wrong account"}" then you need to strip the wrapping quotes such that the variable becomes {"error":"Wrong account"} before you try parsing it into JSON.

For example:

var message; if (event.data.slice(0,1) == '"') { message = JSON.parse(event.data.slice(1,-1)); } else { message = JSON.parse(event.data); }

(see jsfiddle for a working example—note the name change)

(note that this example entirely assumes that if there is a starting quote, there is also an end quote: you might want to build out more logic if that's not consistently true)

更多推荐

本文发布于:2023-08-07 11:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464528.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   空白   意外   JSON   parse

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!