Have a node.js app that is receiving JSON data strings that contain the literal NaN, like
Then your NodeJS app isn't receiving JSON, it's receiving text that's vaguely JSON-like. NaN
is not a valid JSON token.
Three options:
1. Get the source to correctly produce JSON
This is obviously the preferred course. The data is not JSON, that should be fixed, which would fix your problem.
2. Tolerate the NaN
in a simple-minded way:
在解析之前,可以将其替换为null
,例如:
var result = JSON.parse(yourString.replace(/\bNaN\b/g, "null"));
.然后在结果中处理null
.但这是非常简单的,它不允许字符NaN
出现在某个字符串中的可能性.
或者,旋转马特·鲍尔(Matt Ball)的reviver
个 idea (now deleted),您可以将其更改为特殊的字符串(如"***NaN***"
),然后使用复活器将其替换为真正的NaN
:
var result = JSON.parse(yourString.replace(/\bNaN\b/g, '"***NaN***"'), function(key, value) {
return value === "***NaN***" ? NaN : value;
});
...but that has the same issue of being a bit simple-minded, assuming the characters NaN
never appear in an appropriate place.
3. Use (shudder!) eval
If you know and trust the source of this data and there's NO possibility of it being tampered with in transit, then you could use eval
to parse it instead of JSON.parse
. Since eval
allows full JavaScript syntax, including NaN
, that works. Hopefully I made the caveat bold enough for people to understand that I would only recommend this in a very, very, very tiny percentage of situations. But again, remember eval
allows arbitrary execution of code, so if there's any possibility of the string having been tampered with, don't use it.