如何使用 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.stringify
和 JSON.parse
编写一个 replacer 和一个 reviver 函数。替换器可以利用 -0 === 0
、1/0 === Infinity
和 1/-0 === -Infinity
识别负零并将它们转换为特殊字符串。 reviver 应该简单地将特殊字符串转换回 -0
。 Here是 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)"
。
关于javascript - 如何在 JavaScript 中将 JSON 对象字符串化为负零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19577061/