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.

6 comments:

  1. oh thank you sweet baby jesus

    ReplyDelete
  2. why is this even a thing? I wasted over an hour until I found this. Thanks!

    ReplyDelete
    Replies
    1. Glad this could help. I wish the parser gave better feedback and people that write rest apis were better at giving clean output.

      Delete
  3. By those people, you mean Microsoft? I'm using Microsoft's DataContractJsonSerializer to serialise an array of strings: it serialised the array ok, but added a bunch of null characters after the array (only on some computers though, others serialised fine!) Thankyou metric

    ReplyDelete
    Replies
    1. I ran into this issue in ff and chrome was no better. Sometimes the output is just dirty.

      Delete
  4. I also had this problem for a very long period of time, and even your article could not help me to solve it. So, I started to look for another solution and accidentally found this service that had many useful articles about how to parse json in java https://explainjava.com/parse-json-java/ and after reading this articles I finally could solve this problem.

    ReplyDelete

If you found this page useful, or you have any feedback, please leave a comment.