Javascript 为什么 JSON.parse 失败并显示空字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30621802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does JSON.parse fail with the empty string?
提问by Richard
Why does:
为什么:
JSON.parse('');
produce an error?
产生错误?
Uncaught SyntaxError: Unexpected end of input
Wouldn't it be more logical if it just returned null?
如果它刚刚返回不是更合乎逻辑null吗?
回答by bhspencer
As an empty string is not valid JSON it would be incorrect for JSON.parse('')to return nullbecause "null"is valid JSON. e.g.
由于空字符串不是有效的 JSON,因此JSON.parse('')返回是不正确的,null因为它"null"是有效的 JSON。例如
JSON.parse("null");
returns null. It would be a mistake for invalid JSON to also be parsed to null.
返回null。无效的 JSON 也被解析为 null 是错误的。
While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.
虽然空字符串不是有效的 JSON,但两个引号是有效的 JSON。这是一个重要的区别。
Which is to say a string that contains two quotes is not the same thing as an empty string.
也就是说,包含两个引号的字符串与空字符串不同。
JSON.parse('""');
will parse correctly, (returning an empty string). But
将正确解析,(返回一个空字符串)。但
JSON.parse('');
will not.
将不会。
Valid minimal JSON strings are
有效的最小 JSON 字符串是
The empty object '{}'
空的对象 '{}'
The empty array '[]'
空数组 '[]'
The string that is empty '""'
空字符串 '""'
A number e.g. '123.4'
一个数字,例如 '123.4'
The boolean value true 'true'
布尔值真 'true'
The boolean value false 'false'
布尔值 false 'false'
The null value 'null'
空值 'null'
回答by iamawebgeek
Use try-catch to avoid it:
使用 try-catch 来避免它:
var result = null;
try {
// if jQuery
result = $.parseJSON(JSONstring);
// if plain js
result = JSON.parse(JSONstring);
}
catch(e) {
// forget about it :)
}
回答by Seth McClaine
JSON.parseexpects valid notation inside a string, whether that be object {}, array [], string ""or number types (int, float, doubles).
JSON.parse期望字符串中的有效符号,无论是 object {}、 array []、 string""还是数字类型(int、float、doubles)。
If there is potential for what is parsing to be an empty string then the developer should check for it.
如果解析的内容可能是空字符串,那么开发人员应该检查它。
If it was built into the function it would add extra cycles, since built in functions are expected to be extremely performant, it makes sense to not program them for the race case.
如果它被内置到函数中,它会增加额外的周期,因为内置函数被期望具有极高的性能,所以不对它们进行编程是有意义的。
回答by VladNeacsu
Because '' is not a valid Javascript/JSON object. An empty object would be '{}'
因为 '' 不是有效的 Javascript/JSON 对象。空对象将是“{}”
For reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
供参考:https: //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
回答by mikud
For a valid JSON string at least a "{}" is required. See more at the http://json.org/
对于有效的 JSON 字符串,至少需要一个“{}”。在http://json.org/查看更多信息

