javascript JSON 解析意外的非空白字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28329013/
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
JSON parse unexpected non-whitespace character
提问by Raggaer
Currently got the following variable
目前得到以下变量
"{"error":"Wrong account"}"
"{"error":"账号错误"}"
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
console.log 有效,但我收到此错误
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
SyntaxError: JSON.parse: JSON 数据第 1 行第 1 列的意外字符
I think the json format is correct (made using php json_encode) so I dont really know wheres the error
我认为 json 格式是正确的(使用 php json_encode 制作)所以我真的不知道错误在哪里
回答by taswyn
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.
因此,经过一些调试(参见下面该链的反向),结果发现问题是另一条不是 JSON 编码的消息首先被相关代码捕获。
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 @Gumboand @Mattfor 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)
归功于@Gumbo和@Matt的以下答案的混合(因为我们需要实际运行一个测试,但也想检查空/等情况,所以当我们去引用返回时我们不会抛出错误目的)
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.
换句话说,如果console.log(event.data)
显示,从字面上看,"{"error":"Wrong account"}"
那么{"error":"Wrong account"}
在尝试将其解析为 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 jsfiddlefor a working example—note the name change)
(有关工作示例,请参阅jsfiddle— 请注意名称更改)
(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)
(请注意,此示例完全假定如果有起始引号,则还有结束引号:如果这不一致,您可能需要构建更多逻辑)