119

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

bhspencer
  • 13,086
  • 5
  • 35
  • 44
Richard
  • 62,943
  • 126
  • 334
  • 542
  • yeah it seems like a bug in the design of the `parse` function. you can wrap it in `try catch`... but that's ugly :) – vsync Jun 03 '15 at 13:40
  • 3
    It produces an error when anything that isn't valid JSON is passed in, like an empty string. It's actually not that uncommon to create an alias that is wrapped in a try/catch to avoid such errors. – adeneo Jun 03 '15 at 13:42
  • 2
    An empty string is not a valid json, then it fails. Don't think it diserves much more analysis :) – Claudio Redi Jun 03 '15 at 13:42
  • [That's because empty string is invalid as per the JSON grammar](https://www.ietf.org/rfc/rfc4627.txt) – UltraInstinct Jun 03 '15 at 13:45
  • Note that there is a distinction between the empty string which is not valid json and the string which contains two quotes which is valid json e.g. JSON.parse('""'); – bhspencer Jun 03 '15 at 13:53
  • 1
    Please read JSON defenition here http://en.wikipedia.org/wiki/JSON You can check JSON in any JSON Validator, f.e http://jsonlint.com/ if you need empty JSON you have to use {} – Hayk Mantashyan Jun 03 '15 at 13:43
  • This is not correct. A string that contains just two quotes is valid json. Note that such a string is not the same as the empty string. Try JSON.parse('""'); – bhspencer Jun 03 '15 at 13:50
  • '' is not valid JSON – Hayk Mantashyan Jun 03 '15 at 14:01
  • '' is not but '""' is – bhspencer Jun 03 '15 at 14:01
  • 8
    An empty string, as many have mentioned, is not a valid JSON string. Frankly, I think that’s a shortcoming with the specification, as it would have been trivial to return `null`. Requiring the user to check for empty strings or null, or wrapping `JSON.parse` inside `try … 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 Jul 25 '16 at 12:00

5 Answers5

190

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'

bhspencer
  • 13,086
  • 5
  • 35
  • 44
  • 2
    JSON.parse('""') doesn't work I got the error: JSON::ParserError: 757: unexpected token at '""' – Sam Dec 08 '15 at 01:28
  • I just ran `JSON.parse('""');` in the Chrome console and it works as expected. – bhspencer Dec 08 '15 at 02:11
  • Yet a bare `null` value is not valid JSON either and `JSON.parse(null) === null`. JS craziness! – abhillman Dec 03 '16 at 23:37
  • 4
    @abhillman that is because all valid JSON must be a string and null is not a string. – bhspencer Dec 04 '16 at 19:45
  • @bhspencer that is true, yet the more desirable behavior might be for the JS implementation to raise an error. – abhillman Dec 16 '16 at 01:28
  • I came looking for how to represent nothing/empty in JSON, so your "valid minimum strings" was quite useful. Do you have a good source reference for that info? – Stephen R Nov 12 '19 at 17:55
  • It seems that at its most strict, a JSON string must represent an object or array, so the only valid "empties" are `"{}"` and `"[]"`. But common implementations allow for a single valid value (i.e. something you could have as a single element in a JSON-ified array), which is where the latter forms on your list come in. https://stackoverflow.com/a/18419503/339440 – Stephen R Nov 12 '19 at 18:02
  • 1
    @StephenR I suppose it depends of the spec you are using. The spec that started it all by Douglas Crockford is here http://json.org and it allows for the primitives listed in this answer. – bhspencer Nov 13 '19 at 17:10
  • 5
    @bhspencer pshaw. Who you gonna believe, me or some random guy on the Internet who invented the standard? ;-) – Stephen R Nov 13 '19 at 17:43
20

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 :)
}
iamawebgeek
  • 2,713
  • 1
  • 18
  • 34
1

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.

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
  • 1
    This is not correct. Try parsing a string that contains two quotes JSON.parse('""'); – bhspencer Jun 03 '15 at 13:51
  • 2
    Json is not a markup language, it would be more accurate to say JSON.parse expects a string that conforms to the specification. – bhspencer Jun 03 '15 at 14:02
  • 2
    JSON doesn't support the int primitive type. Its called "number" and supports real values not just ints. – bhspencer Jun 03 '15 at 14:11
  • JSON.parse accepts number too, i.e `JSON.parse(123.45)` -> 123.45, at least in Firefox – fantom Jan 14 '20 at 12:23
-2

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

VladNeacsu
  • 1,268
  • 16
  • 33
-2

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

mikud
  • 50
  • 3