Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSON parsing not fail on the first character for strings starting with "t"?

I'll try to clarify what I mean as quickly as possible.

JSON.parse("te")
VM297:1 Uncaught SyntaxError: Unexpected token e in JSON at position 1
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

JSON.parse("ce")
VM342:1 Uncaught SyntaxError: Unexpected token c in JSON at position 0
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

As you can see, the parsing fails at position 0 for the string "ce" and at position 1 for the string "te". This means that the parser believes that there is some legal JSON that starts with the character "t". Does anybody know what that would be? Or why the parser fails a character later for t?

like image 869
Cruncher Avatar asked Sep 24 '19 19:09

Cruncher


People also ask

Why does JSON parse not work?

Null values and empty strings (“”) are valid JSON values, but the state of being undefined is not valid within JSON. JSON. parse() will fail if it encounters an undefined value.

When can JSON parse fail?

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.

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.

Can JSON parse special characters?

parse needs to get a string which consists only of unicode characters (see Json parsing with unicode characters). For you the JSON. parse method fails, because your string contains non-unicode characters.


2 Answers

The keyword true starts with "t". Thus until the parser sees the "e", it doesn't know the syntax is invalid.

The error is somewhat fascinating because it reports "e" as being a token, which is not the way I'd implement a JSON parser. That seems to be a Node/V8 thing, as Firefox rejects the whole token starting from position 1 (the "t").

You can double-check this answer by trying JSON.parse("nulp"); Node errors on the "p".

like image 66
Pointy Avatar answered Sep 28 '22 04:09

Pointy


The full JSON syntax is as follows:

JSON = null
    or true or false
    or JSONNumber
    or JSONString
    or JSONObject
    or JSONArray

so the compiler will deal with t, n , f as a valid start for a JSON string. for more information check: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

like image 22
Rabie Dogho Avatar answered Sep 28 '22 04:09

Rabie Dogho