"SyntaxError: Unexpected token :" when inputting { "a": "", "b": "" } json in console "SyntaxError: Unexpected token :" when inputting { "a": "", "b": "" } json in console json json

"SyntaxError: Unexpected token :" when inputting { "a": "", "b": "" } json in console


You can't execute JSON in the console. The JavaScript engine thinks its a block statement, with a label.

So this:

{    "a": "", "b": ""}

is interpreted as a block statement. The "a": part is interpreted as a label. The "", "b"part is interpreted as an expression (two string literals and a comma operator in-between). Now the second : character is invalid in that position... Next, the "a" is interpreted as a string literal, and the : is not valid at that position.

You work with JSON like so:

  1. You put it in a .json file,
  2. You retrieve it via Ajax as a string,
  3. You parse the string into an object with JSON.parse().

(You can also keep JSON data as a string in a variable, for instance, or in the localStorage object. Either way, in regard to JavaScript, JSON data should always come as a string value.)


Actually, for one-off testing (my main use of the debug console), you can enter JSON object syntax, but you have to assign it to a variable:

> var x ={    "a": "",    "b": ""  }undefined> xObject  a: ""  b: ""  __proto__: Object