Google analytics code

Thursday, January 23, 2014

Javascript: Problems, trouble, issues parsing JSON data / Unexpected token

I ran into an issue trying to parse a JSON string that made very little sense. Normally when you have a token in the JSON response that doesn't work the error will include that character. This time it gave me nothing.

// This is all you have to do
JSON.parse(jsonObject);

After 4 hours and much googling I had no answer. I though for some reason the server response had the wrong type of quotes on it, but turned out to be something very left field.

I used JSON.stringify() on the server response and saw something really weird on the end of the string that wasn't showing up by looking at the response.

// What is this?!
'"timeCreated\":1390518047098}\u0000\u0000\'

The \u0000 character was choking the parser and wasn't showing up as a bad token. This is the unicode character for null. Not sure why it was on the response but it was causing the problem. Running this cleaned up the problem.

// Take out the garbage
[server response] = [server response].replace(/\u0000/g, "")

As a safety measure it's good to have a method you can use to clean your JSON strings before trying to parse them.

Friday, January 10, 2014

Javascript: Quick Date timestamp

I wanted to find a quick way to compare two dates. The easiest way is to use their unix timestamp. If the date exists as an object you can use .getTime() to retrieve the number of milliseconds that have passed since epoch time.

You can retrieve that number even faster with the following bit of code

+new Date

I found the tip here and wanted to surface it.