How to associate a JSON object with a negative zero in JavaScript?

How can I use JSON.stringify to convert a negative zero to a string (-0)? It looks like JSON.stringify will convert negative zero to a string representing positive. Any idea for a good workaround?

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;
}
+4
source share
1 answer

You can write a replacement and reviver function for JSON.stringifyand JSON.parse, respectively. The substitute can use -0 === 0, 1 / 0 === Infinityand 1 / -0 === -Infinityto determine negative zeros and convert them to a special line. The examiner should simply convert the special string back to -0. Here is the jsfiddle.

Code:

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);

Output:

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

"NEGATIVE_ZERO", , "(-0)".

+5

All Articles