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

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".

This question is related to javascript json

The answer is


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


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 :)
}

For a valid JSON string at least a "{}" is required. See more at the http://json.org/


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.