JSON.stringify将Infinity转换为null [英] JSON.stringify converting Infinity to null

查看:1016
本文介绍了JSON.stringify将Infinity转换为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有JavaScript对象说:

I have JavaScript Object say:

var a = {b: Infinity, c: 10};

当我这样做时

var b = JSON.stringify(a);

它返回以下内容

b = {b:null,c:10};

b = "{"b":null, "c":10}";

JSON.stringify如何将对象转换为字符串?

How is the JSON.stringify converts the object to strings?

我尝试 MDN解决方案

function censor(key, value) {
  if (value == Infinity) {
    return "Infinity";
  }
  return value;
}
var b = JSON.stringify(a, censor);

但是在这种情况下我必须返回字符串Infinity而不是 Infinity 。如果我返回Infinity,它会再次将Infinity转换为null。

But in this case I have to return the string "Infinity" not Infinity. If I return Infinity it again converts Infinity to null.

如何解决此问题。

推荐答案

与所述的其他答案一样, Infintity 不是JSON可以存储为值的值的一部分。

Like the other answers stated, Infintity is not part of the values JSON can store as value.

您可以在解析JSON时反转审查方法:

You can reverse the censor method on parsing the JSON:

var c = JSON.parse(
          b,
          function (key, value) {
            return value === "Infinity"  ? Infinity : value;
          }
        );

这篇关于JSON.stringify将Infinity转换为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆