最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON.stringify(undefined) is not a string - Stack Overflow

programmeradmin3浏览0评论

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?

Share Improve this question asked Jul 3, 2013 at 16:27 Web_DesignerWeb_Designer 74.6k93 gold badges209 silver badges266 bronze badges 5
  • 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 the replacer. – Jonathan Lonowski Commented Jul 3, 2013 at 16:31
  • 4 JSON.stringify(undefined) it the same as calling JSON.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
Add a ment  | 

3 Answers 3

Reset to default 7

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

发布评论

评论列表(0)

  1. 暂无评论