Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm getting errors, in both chrome and firefox developer tools, when trying to evaluate the following:

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

jsonlint.com tells me it's valid. Putting this code in an actual javascript file and running it works fine. The strangeness shows up only when I run this in the console in chrome developer tools or firebug. What's going on here?

like image 316
morgancodes Avatar asked May 10 '12 16:05

morgancodes


People also ask

How do I fix unexpected token in JSON error?

The "Unexpected token u in JSON at position 0" error occurs when we pass an undefined value to the JSON. parse or $. parseJSON methods. To solve the error, inspect the value you're trying to parse and make sure it's a valid JSON string before parsing it.

How do I fix an unexpected token syntax error?

As you write your JavaScript application, the unexpected token error always occurs because JavaScript expected a specific syntax that's not fulfilled by your current code. You can generally fix the error by removing or adding a specific JavaScript language symbol to your code.

What does this mean SyntaxError unexpected token in JSON at position 0?

Re: Unexpected token in JSON at position 0 This usually means that an error has been returned and that's not valid JSON. Check the browser developer tools console and network tabs. Turn on Debugging and (after reproducing the error) check the web server error logs.

What does SyntaxError unexpected token mean?

The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.


2 Answers

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

like image 112
Šime Vidas Avatar answered Oct 29 '22 15:10

Šime Vidas


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

> x
Object
  a: ""
  b: ""
  __proto__: Object
like image 30
Andy Avatar answered Oct 29 '22 17:10

Andy