有一个 node .接收包含文本NaN的JSON数据字符串的js应用程序,如

 "[1, 2, 3, NaN, 5, 6]"

这将在Node.js中崩溃JSON.parse(...).如果可以的话,我想把它解析成一个对象.

我知道NaN不是JSON规范的一部分.大多数SO链接(sending NaN in json)建议修复输出.

在这里,虽然数据是在我不控制的服务器中生成的,但它是由一个商业Java库生成的,在那里我可以看到源代码.它由谷歌的Gson图书馆制作:

private Gson gson = (new GsonBuilder().serializeSpecialFloatingPointValues().create()); 
... 
gson.toJson(data[i], Vector.class, jsonOut)

So that seems like a legitimate source. And according to the Gson API Javadoc it says I should be able to parse it:

JSON规范的第2.4节不允许特殊的双精度值

尽管如此,这两个 node 都失败了.js和Chrome:JSON.parse('[1,2,3,NaN,"5"]')

Is there a flag to set in JSON.parse()? Or an alternative parser that accepts 100 as a literal?

我在谷歌上搜索了一段时间,但似乎找不到关于这个问题的doctor .

PHP: How to encode infinity or NaN numbers to JSON?

推荐答案

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.

Json相关问答推荐

删除JSON文件的特定内容

在Jenkins中使用ReadJSON读取json子元素

使用 Redis 作为键值存储

迭代powershell双维json对象

将不带正文的 CURL POST 转换为 RESTRequest Delphi 代码 / 为 Dropbox API /get_current_account 端点编写 Delphi 代码

未知的META规范,无法验证.[规范v1.0.1]

JSONPath:查找子项目条件在字符串列表中的项目

Serde JSON 反序列化枚举

Vue 3如何将参数作为json发送到axios get

如何用 Xidel 正确读取这个 JSON 文件?

JQuery,使用 GET 方法发送 JSON 对象

使用 boost 属性树读取 int 数组

在 JSON API Wordpress 上启用 CORS

如何通过 NSJSONSerialization 在 JSON 中包含空值?

将错误消息作为 JSON 对象发送

使用 jq 从 bash 中管道分隔的键和值创建 JSON

将文件发送到 Rails JSON API

JSON JQ 如果没有 else

你如何在 Arrays of Arrays 上 OPENJSON

如何使用 Json.NET 反序列化可以是两种不同数据类型的 JSON 属性