Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSON.parse fail with the empty string? [duplicate]

Why does:

JSON.parse('');

produce an error?

Uncaught SyntaxError: Unexpected end of input

Wouldn't it be more logical if it just returned null?

EDIT: This is not a duplicate of the linked question. While the topic of minimal valid json is related to this question it does not get at the "why".

like image 967
Richard Avatar asked Jun 03 '15 13:06

Richard


People also ask

Why is JSON parse failing?

The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.

Is an empty string a valid JSON key?

Tl;dr Yes it is.

What error does JSON parse () throw when the string to parse is not valid JSON?

Exceptions. Throws a SyntaxError exception if the string to parse is not valid JSON.


2 Answers

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'

like image 185
bhspencer Avatar answered Oct 16 '22 14:10

bhspencer


Use try-catch to avoid it:

var result = null;
try {
  // if jQuery
  result = $.parseJSON(JSONstring);
  // if plain js
  result = JSON.parse(JSONstring);
}
catch(e) {
  // forget about it :)
}
like image 17
iamawebgeek Avatar answered Oct 16 '22 13:10

iamawebgeek