Why does JSON.parse fail with the empty string?
This question already has an answer here:
As an empty string is not valid JSON it would be incorrect for JSON.parse('')
to return null
because "null"
is valid JSON. eg
JSON.parse("null");
returns null
. It would be a mistake for invalid JSON to also be parsed to null.
While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.
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
The empty object '{}'
The empty array '[]'
The string that is empty '""'
A number eg '123.4'
The boolean value true 'true'
The boolean value false 'false'
The null value 'null'
使用try-catch避免它:
var result = null;
try {
// if jQuery
result = $.parseJSON(JSONstring);
// if plain js
result = JSON.parse(JSONstring);
}
catch(e) {
// forget about it :)
}
JSON.parse
expects valid notation inside a string, whether that be object {}
, array []
, string ""
or number types (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.
链接地址: http://www.djcxy.com/p/8004.html上一篇: 如何绕过Access