As an empty string is not valid JSON it would be incorrect for JSON.parse('')
to return null
because "null"
is valid JSON. e.g.
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 e.g. '123.4'
The boolean value true 'true'
The boolean value false 'false'
The null value 'null'
parse
function. you can wrap it intry catch
... but that's ugly :) – vsyncnull
. Requiring the user to check for empty strings or null, or wrappingJSON.parse
insidetry … catch
should have unnecessary. The fact that the question had to be asked also suggests that it’s not intuitive. In any case, you can use:JSON.parse(data||'{}')
to coerce an empty string to something safe. – Manngo