Why does:
JSON.parse('');
produce an error?
Uncaught SyntaxError: Unexpected end of input
Wouldn't it be more logical if it just returned null
?
Why does:
produce an error?
Wouldn't it be more logical if it just returned |
|||
As an empty string is not valid JSON it would be incorrect for
returns 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.
will parse correctly, (returning an empty string). But
will not. Valid minimal JSON strings are The empty object The empty array The string that is empty A number e.g. The boolean value true The boolean value false The null value |
|||||||||||||||||||||
|
Use try-catch to avoid it:
|
|||
|
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. |
|||||||||||||
|
Because '' is not a valid Javascript/JSON object. An empty object would be '{}' For reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse |
|||
|
For a valid JSON string at least a "{}" is required. See more at the http://json.org/ |
|||||
|
parse
function. you can wrap it intry catch
... but that's ugly :) – vsync Jun 3 '15 at 13:40