7

JSON undefined errors

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?

6
  • To get around it perhaps try JSON.stringify( myvar ? myvar : "*ERROR*" ) Commented Jul 3, 2013 at 16:29
  • 2
    or JSON.stringify( myvar || "*ERROR*" ) 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 the replacer. Commented Jul 3, 2013 at 16:31
  • 4
    JSON.stringify(undefined) it the same as calling JSON.stringify() (i.e. without any arguments). Commented Jul 3, 2013 at 16:32
  • The types from "/node_modules/typescript/lib/lib.es5.d.ts" do not indicate this possibility... Commented Jul 7, 2023 at 15:19

3 Answers 3

6

undefined is not valid JSON, so the function is working properly.

http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example

Sign up to request clarification or add additional context in comments.

Comments

3
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.

Comments

2

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.

3 Comments

Javascript is a bit weird. Properties can exist and still be undefined: window.x = undefined; console.log(window.x); console.log(x in window); // undefined, true
true, similaraly undefined can be defined undefined = "hello". Got to love JavaScript
As of the most recent versions of ECMAScript undefined is not writable, so that would leave the value of undefined unchanged, but it's true that in old versions that would overwrite the value of undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.