javascript node.js 中出现奇怪的 JSON.parse() 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9712849/
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
Strange JSON.parse() error in node.js
提问by buschtoens
I'm retrieving some stringifyed JSON via TCP in node.js an want to parse it. So my approach is similiar to this. I shortend and simplified it, so you don't have to know the surrounding logic.
我正在 node.js 中通过 TCP 检索一些字符串化的 JSON 并想解析它。所以我的方法与此类似。我缩短并简化了它,因此您不必了解周围的逻辑。
socket.on("data", function(data) {
console.log(data.toString()); // Shows the original stringifyed version
console.log(JSON.parse(data.toString())); // Doesn't work
});
The complete (beautified) JSON is this. As you can see, there are no errors.
完整的(美化的)JSON 是这样的。如您所见,没有错误。
{
"result": "success",
"source": "chat",
"success": {
"message": "test",
"time": 1331770513,
"player": "silvinci"
}
}
But JSON.parse(data.toString())
always throws me this dumb error:
但JSON.parse(data.toString())
总是给我抛出这个愚蠢的错误:
{"result":"success","source":"console","success":{"time":1331762264,"line":"20
^
SyntaxError: Unexpected token {
at Object.parse (native)
at Socket.<anonymous> (/home/node/api.js:152:35) // irrelevant from here on
at Socket.emit (events.js:67:17)
at TCP.onread (net.js:347:14)
So I thougt: "What could be wrong with the JSON-String. Let's try it directly. Should not work." Surprise, Surprise! It worked. Why does it work when I directly enter the String?
所以我想:“JSON-String 可能有什么问题。让我们直接尝试。应该行不通。” 惊喜,惊喜!有效。为什么直接输入String会起作用?
回答by buschtoens
Thanks to @Felix KlingI found my bug. It's very important to filter unescaped characters, especially outside the stringified JSON. I didn't and overlooked an invisible linebreak right after the stringified JSON.
感谢 @ Felix Kling我发现了我的错误。过滤未转义的字符非常重要,尤其是在字符串化 JSON 之外。在字符串化的 JSON 之后,我没有并忽略了一个不可见的换行符。
This is the fix:
这是修复:
socket.on("data", function(data) {
console.log(data.toString()); // Shows the original stringified version
console.log(JSON.parse(data.toString().slice(0, -4))); // Trim the sequence "\r\n" off the end of the string
});
Please note, that this onlyworks for me, as I have a very specialized case. The server is always responding in lines of JSON, that are terminated with an \r\n
- not the whitespace characters, but literally backslash r and backslash n.
Your code may (or probably) fail due to other errors. But checking the server's response is a good starting point when you get parsing errors.
请注意,这仅适用于我,因为我有一个非常专业的案例。服务器总是以 JSON 行响应,这些行以\r\n
- 不是空白字符终止,而是字面上的反斜杠 r 和反斜杠 n。
您的代码可能(或可能)由于其他错误而失败。但是当您遇到解析错误时,检查服务器的响应是一个很好的起点。
As @Zackcorrectly pointed out, this is a more general fix for removing unintended whitespace:
正如@ Zack正确指出的那样,这是删除意外空白的更通用的修复方法:
JSON.parse(data.toString().trim());
回答by user3413723
I had a similar issue. For a more general solution, this will work too. It takes off all whitespace before and after the string so you don't have to do the specific substring length.
我有一个类似的问题。对于更通用的解决方案,这也将起作用。它会去除字符串前后的所有空格,因此您不必执行特定的子字符串长度。
JSON.parse(data.trim());
回答by xameeramir
Instead of blindly removing last 4 chars, I suggest to remove the offending chars only:
我建议不要盲目地删除最后 4 个字符,而是只删除有问题的字符:
socket.on("data", function(data) {
console.log(data.toString()); // Shows the original stringified version
console.log(JSON.parse(data.toString().replace('\r','').replace('\n',''))); // Trim the sequence "\r\n" off the end of the string
});