JSON is meant to be language agnostic. It already supports null. Supporting undefined as well would impose the handling of one of JavaScript's idiosyncrasies on other languages, which defeats the purpose of easy interoperability.
'JSON's design goals were for it to be minimal, portable, textual, and
a subset of JavaScript.'
As for not throwing an error, well
var x = { foo: undefined };
x.foo === undefined; // true
var json = JSON.stringify(x);
var y = JSON.parse(json);
y.foo === undefined; // true
So JSON.stringify can create a string that represents the value x.
Throwing an error would not be useful in this case. In fact JSON.stringify
ignores all values that don't have a JSON representation, so functions
are ignored to. This makes it easy to serialise object data, for example.
Finally, bear in mind that JSON.stringify takes a replacer function as
an argument which can be used to alter the way stringification takes place.
So to make JSON.stringify throw existing properties with an undefined value:
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
Or to replace with null:
var replacer = function(key, value){
if(value === undefined){
return null;
}
return value;
};
var x = {foo: undefined};
JSON.stringify(x, replacer); // '{"foo":null}'
undefinedit would also have to be converted to a string. What happens if I'm going to transfer a string which has the same value as the string-representation ofundefined? How to distinguish which"undefined"is which. But if you really want to go this way then you can pass areplacerfunction as the second parameter ofJSON.stringify(value[, replacer[, space]])-> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…undefinedis not a defined value for JSON. If you really need to change the defined behaviour of JSON then you will have to use areplacerfunction.