JSON.stringify (undefined) is not a string

JSON undefined errors

JSON.stringify(null) returns a null string.

JSON.stringify(undefined) returns undefined . Should I return an undefined string?

Parsing an undefined value or an undefined string gives a SyntaxError .

Can someone explain why JSON is choking on undefined and how to get around it when building / analyzing values?

+6
source share
3 answers

undefined not valid JSON, so the function works correctly.

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

+7
source
 if(JSON.stringify(input) === undefined) { // error handle } 

or

 if(input === undefined) { // error handle } else { JSON.stringify(input); } 

Unfortunately. Sometimes life is difficult. This is pretty much what you need to do.

+2
source

The reason for this is because null caused by a variable that doesn't matter, so when converting to JSON it gives you JSON that doesn't matter, undefined means it doesn't exist at all, so you can't create a JSON object of what doesn't exist. Just check

  if(typeof myvar === 'undefined') 

before starting and handling the error in the code. As a rule, try to avoid undefined in your JS, they can create strange things everywhere and do NOT match null and are usually handled differently.

+1
source

Source: https://habr.com/ru/post/948642/


All Articles