Why does JSON.stringify ignore keys with undefined values?

To be more precise, I understand why this is technically happening - since undefinedit is not a valid JSON type:

var breakfast = {
    "cereal" : "fruit loops",
    "pastry" : undefined
};

console.log(breakfast);
// -> { cereal: 'fruit loops', pastry: undefined }

console.log(JSON.stringify(breakfast));
// -> {"cereal":"fruit loops"}

My question is: why is this considered acceptable behavior? There are obvious reasons why I would like to pass undefinedas part of an API or something else. This seems a little dangerous - why shouldn't a function cause an error instead of taking it impudently to change my data without warning? This is like a thread with JS.

+4
source share
2 answers

The answer to this question lies in the specification of ECMA-262 . The section 24.3.2 JSON.stringify ( value [ , replacer [ , space ] ] )in the specification clearly states that:

NOTE 2

undefined .

:

5

, JSON (, undefined ), . undefined. null. .

, JSON.stringify(), , ECMA.

, , - , :

24.3.2 4.b.5.g

undefined, PropertyList

+5

JSON . null. undefined JavaScript , .

JSON , , ,   JavaScript. '

,

var x = { foo: undefined };
x.foo === undefined; // true
var json = JSON.stringify(x);
var y = JSON.parse(json);
y.foo === undefined; // true

, JSON.stringify , x. . JSON.stringify , JSON, . , .

, , JSON.stringify replacer , . , JSON.stringify undefined:

var replacer = function(key, value){
    if(value === undefined){
        throw 'JSON.stringify: bad property: ' + key;
    }
    return value;
};

var x = {foo: undefined};
JSON.stringify(x, replacer);
// uncaught exception: JSON.stringify: bad property: foo

null:

var replacer = function(key, value){
    if(value === undefined){
        return null;
    }
    return value;
};

var x = {foo: undefined};
JSON.stringify(x, replacer); // '{"foo":null}'
+2

All Articles