简体   繁体   English

JSON.stringify(undefined)不是字符串

[英]JSON.stringify(undefined) is not a string

JSON未定义错误

JSON.stringify(null) returns the string null . JSON.stringify(null)返回字符串null

JSON.stringify(undefined) returns the value undefined . JSON.stringify(undefined)返回值undefined Shouldn't it return the string undefined ? 它不应该返回字符串 undefined吗?

Parsing the value undefined or the string undefined gives a SyntaxError . 解析值undefined或字符串undefined给出了一个SyntaxError

Could someone explain why JSON chokes on undefined and how to get around it when stringifying / parsing values? 有人可以解释为什么JSON会在undefined窒息,以及在字符串化/解析值时如何绕过它?

undefined is not valid JSON, so the function is working properly. undefined是无效的JSON,因此该函数正常工作。

http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example http://en.wikipedia.org/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. 原因是null是由没有值的变量引起的,所以当转换为JSON时,它会为你提供没有值的JSON,undefined意味着它根本不存在,所以你可以不要创建一个不存在的JSON对象。 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. 通常尽量避免在JS中使用undefined ,它们可以在整个地方发生奇怪的事情,并且与null不同,并且通常以不同的方式处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM