如何在JavaScript中使用负零字符串化JSON对象?

时间:2013-10-24 21:30:28

标签: javascript json

如何使用JSON.stringify将负零转换为字符串(-0)?似乎JSON.stringify将负零转换为表示正数的字符串。想要一个好的解决方法吗?

var jsn = {
    negative: -0
};
isNegative(jsn.negative) ? document.write("negative") : document.write("positive");
var jsonString = JSON.stringify(jsn),
    anotherJSON = JSON.parse(jsonString);
isNegative(anotherJSON.negative) ? document.write("negative") : document.write("positive");

function isNegative(a)
{
    if (0 !== a)
    {
        return !1;
    }
    var b = Object.freeze(
    {
        z: -0
    });
    try
    {
        Object.defineProperty(b, "z",
        {
            value: a
        });
    }
    catch (c)
    {
        return !1;
    }
    return !0;
}

2 个答案:

答案 0 :(得分:5)

您可以分别为JSON.stringifyJSON.parse编写替换函数和复活函数。替换者可以利用-0 === 01 / 0 === Infinity1 / -0 === -Infinity来识别负零并将其转换为特殊字符串。 reviver应该只将特殊字符串转换回-0Here是jsfiddle。

代码:

function negZeroReplacer(key, value) {
    if (value === 0 && 1 / value < 0) 
        return "NEGATIVE_ZERO";
    return value;
}

function negZeroReviver(key, value) {
    if (value === "NEGATIVE_ZERO")
        return -0;
    return value;
}

var a = { 
        plusZero: 0, 
        minusZero: -0
    },
    s = JSON.stringify(a, negZeroReplacer),
    b = JSON.parse(s, negZeroReviver);

console.clear();
console.log(a, 1 / a.plusZero, 1 / a.minusZero)
console.log(s);
console.log(b, 1 / b.plusZero, 1 / b.minusZero);

输出:

Object {plusZero: 0, minusZero: 0} Infinity -Infinity
{"plusZero":0,"minusZero":"NEGATIVE_ZERO"} 
Object {plusZero: 0, minusZero: 0} Infinity -Infinity

我将负零转换为"NEGATIVE_ZERO",但您可以使用任何其他字符串,例如"(-0)"

答案 1 :(得分:0)

您可以将JSON.stringify与替换函数一起使用,以将负零更改为特殊字符串(如先前的回答所述),然后使用全局字符串替换将这些特殊字符串更改为结果json中的负零。串。例如:

function json(o){
 return JSON.stringify(o,(k,v)=>
  (v==0&&1/v==-Infinity)?"-0.0":v).replace(/"-0.0"/g,'-0')
}

console.log(json({'hello':0,'world':-0}))