如何在 JavaScript 中将 JSON 对象字符串化为负零

How do I stringify a JSON object with a negative zero in JavaScript?

本文关键字:字符串 对象 JSON JavaScript 中将      更新时间:2023-09-26

如何使用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;
}

您可以分别为JSON.stringifyJSON.parse编写替换器和齐磊函数。替换器可以利用-0 === 01 / 0 === Infinity1 / -0 === -Infinity来识别负零并将它们转换为特殊的字符串。齐磊应该简单地将特殊字符串转换回-0。这是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)" .

您可以使用 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}))