JSON.stringify(null)
returns the string null
.
JSON.stringify(undefined)
returns the value undefined
. Shouldn't it return the string undefined
?
Parsing the value undefined
or the string undefined
gives a SyntaxError
.
Could someone explain why JSON chokes on undefined
and how to get around it when stringifying / parsing values?
JSON.stringify(null)
returns the string null
.
JSON.stringify(undefined)
returns the value undefined
. Shouldn't it return the string undefined
?
Parsing the value undefined
or the string undefined
gives a SyntaxError
.
Could someone explain why JSON chokes on undefined
and how to get around it when stringifying / parsing values?
-
To get around it perhaps try
JSON.stringify( myvar ? myvar : "*ERROR*" )
– PP. Commented Jul 3, 2013 at 16:29 -
2
or
JSON.stringify( myvar || "*ERROR*" )
– Ben Commented Jul 3, 2013 at 16:30 -
5
"Shouldn't it return the string undefined?" No.
undefined
isn't recognized by JSON.JSON.stringify({ foo: 'bar', baz: undefined }) === '{"foo":"bar"}'
.undefined
is also how you skip values with thereplacer
. – Jonathan Lonowski Commented Jul 3, 2013 at 16:31 -
4
JSON.stringify(undefined)
it the same as callingJSON.stringify()
(i.e. without any arguments). – Felix Kling Commented Jul 3, 2013 at 16:32 - The types from "/node_modules/typescript/lib/lib.es5.d.ts" do not indicate this possibility... – Eric Burel Commented Jul 7, 2023 at 15:19
3 Answers
Reset to default 7undefined
is not valid JSON, so the function is working properly.
http://en.wikipedia/wiki/JSON#Data_types.2C_syntax_and_example
if(JSON.stringify(input) === undefined) {
// error handle
}
or
if(input === undefined) {
// error handle
}
else {
JSON.stringify(input);
}
Sorry. Life is hard sometimes. This is pretty much what you have to do.
The reason for this is that null
is caused by a variable that doesn't have a value, so when converted to JSON it gives you JSON that doesn't have a value, undefined means it doesn't exist at all, so you can't create a JSON object of something that doesn't exist. Just check
if(typeof myvar === 'undefined')
before you run it and handle the error gracefully in the code.
Generally try to avoid undefined
in your JS they can to weird things all over the place, and are NOT the same as null
and are usually handled differently.