Thursday, September 25, 2014

My struggle with JSON

We all use developer tools. Console is of tremendous help when it comes to trying JavaScript snippets. Sometimes however something relatively simple e.g. like typing in JSON throws errors for apparently no reason. I had one of these moments and as usual started digging to see why it was happening. Ok, hit F12 in Chrome and type in:

{ “name” : “homer” }

Plain, old JSON it seems, nothing fancy. However you will be greeted with:

It is valid JSON so what gives? First thing that came to my mind was hidden characters. It’s (not so) well know fact that JSON is not quite a subset of JavaScript. JSON allows certain characters in a String and JavaScript doesn't. Given that one of the strings above contain Line Separator (line feed, carriage return etc.) this would sure spell trouble. Even though “Unexpected token :” would point problem to “:” rather than anything else I decided to check strings for any whitespace characters.

Fired up my trusted Notepad++ to see what Chrome doesn't show, but with no luck. No hidden characters of any type.

To make the matter worse running:

{ name:”homer”}

worked just fine. Almost fine actually, as the line was returning a “string” rather than object:

Why string though? Let me explain.. Using curly braces in console the way I originally did, creates a block statement. It is not parsed in expression context and so it does not create an Object. It does very much the same as I would execute:

It produces exactly same output so error pointing to “:”. If you look at this however it suddenly stops making sense. We simply creating here a string, followed by a colon, followed by another string. Clearly wrong.

Now, { name:”homer”} however was working. It was returning string rather than object, and for a good reason. Curly braces create block statement and so lets strip those and run:

You should see the problem by now. Obviously what I was trying to do here is to create a label followed by string “homer” and so “homer” was spit out to console as expected. If you are not familiar with labels in JS they are used e.g. to break out of loops e.g.:

var i, j;

    for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
        loop2: for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
            if (i == 1 && j == 1) {
                continue loop1;
            console.log("i = " + i + ", j = " + j);

// Output is:
// "i = 0, j = 0"
// "i = 0, j = 1"
// "i = 0, j = 2"
// "i = 1, j = 0"
// "i = 2, j = 0"
// "i = 2, j = 1"
// "i = 2, j = 2"
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"

So there it is. I was creating block statement with invalid syntax hence the error. Mistake that I won’t do again.

No comments:

Post a Comment