I use Windows 7 64 bit, and Firefox 32.
So I have read that JSON.parse can't handle something like JSON.parse("{ 'a': undefined }";
But when using JSON.stringify in the following context, I get undefined:
console.log("'abc': " + JSON.stringify(this.nothing));
results in
"'abc': undefined"
I'm creating my object-strings in my own functions, but for simplicity in those functions I'm using JSON.stringify for some variables.
I assumed that would bring me on the secure side.
I use Windows 7 64 bit, and Firefox 32.
So I have read that JSON.parse can't handle something like JSON.parse("{ 'a': undefined }";
But when using JSON.stringify in the following context, I get undefined:
console.log("'abc': " + JSON.stringify(this.nothing));
results in
"'abc': undefined"
I'm creating my object-strings in my own functions, but for simplicity in those functions I'm using JSON.stringify for some variables.
I assumed that would bring me on the secure side.
Share Improve this question asked Mar 25, 2015 at 3:23 JohnJohn 60610 silver badges29 bronze badges2 Answers
Reset to default 3You're using the JSON facility incorrectly:
console.log(JSON.stringify({ abc: this.nothing }));
That will give you the JSON string "{}"
, which is correct, because ({}).abc
is undefined
. The JSON spec includes no provision for undefined
; the only scalar values allowed are strings, numbers, booleans, and null
. Thus a JavaScript property whose value is undefined
is "serialized" as not being in the object at all.
Don't use JSON.stringify()
piecemeal. Create your JavaScript object structure and then stringify the whole thing.
You can't use JSON.stringify
to turn values into JSON that is not supported. The value undefined
is one of those values.
If you use for example JSON.stringify(null)
you will get the string "null"
back because that is a supported value. You can see at http://json/ what the supported values are.
If you use JSON.stringify(undefined)
you won't get the string "undefined"
back. The unsuppored value is omitted from the result, and as that makes the result pletely empty (not an empty object or array), the result is the value undefined
.