Search code examples
javascriptjsonecmascript-5stringify

Questions about JSON.stringify in ECMAScript


I'm watching MDN's "Using native JSON". And I've 3 questions about the JSON.stringify method.

Question 1:

var foo = {
    "foundation": "Mozilla",
    "model": "box",
    "week": 45,
    "transport": "car",
    "month": 7
},
    censor = function (key, value) {
        if (typeof value === 'string') {
            return;
        }
        return value;
    };
console.log(JSON.stringify(foo, censor)); // String: {"week":45,"month":7}

Codes above work fine. But why can't codes below work fine?

var foo = {
    "foundation": "Mozilla",
    "model": "box",
    "week": 45,
    "transport": "car",
    "month": 7
},
    censor = function (key, value) {
        if (typeof value !== 'string') {
            return;
        }
        return value;
    };
console.log(JSON.stringify(foo, censor)); // undefined

Question 2:

Please observe codes below:

var foo = {
    "foundation": "Mozilla",
    "model": "box",
    "week": 45,
    "transport": "car",
    "month": 7
},
    censor = function (key, value) {
        return 2;
    };
console.log(JSON.stringify(foo, censor)); // String: 2

I think my codes should get string below because "If you return a Number, the string corresponding to that number is used as the value for the property when added to the JSON string." (quoted from https://developer.mozilla.org/En/Using_native_JSON).

{"foundation":2,"model":2,"week":2,"transport":2,"month":2}

But I just get a string 2. Why?

Question 3:

If I wanna get {"foundation":2,"model":2,"week":2,"transport":2,"month":2}, how should I change the codes?

Thank you very much!


Solution

    1. foo is an object ({…}). Objects are not strings. You censor the outer object, so it never gets recursed into.
    2. Because you return 2 for foo instead of recursing into it
    3. Test if it is a string or a number (instead of testing if it isn't a string) then return 2