JSON Parsing – Unexpected Token

This is a quick note because I just had this issue parsing JSON that was returned to me from the server. I was attempting to use JSON.parse, jQuery.parseJSON, and eval()… but i kept getting a range of errors depending how i attempted to manipulate it:

  • Unexpected Token {
  • Unexpected Token :
  • Unexpected Token ILLEGAL

And one or two more.  I searched a bunch of pages and it seems other people have this as well.  Also, my JSON validated with this validator.

Anyway, the solution for me, and others it seems, was to replace newline characters.  I was able to dig into the error a little bit using Chrome’s developer tools console to try to get the string to parse. The error allowed for expanding and hidden deeper in the stack trace was an error that suggested there were newline characters.  I also saw another post where someone had strings ending with the C string terminator ‘\0’

So, if you’re having this issue, try to get the JSON to parse in the console and see if there is some random character put in there that needs to be replaced.

success: function(response) {
   // REPONSE data has newlines!!  replace or it won't parse!
   var data = $.parseJSON(response.replace(/\n/g,"")); 
   // or use JSON.parse(...) if you're not using jquery and have a modern browser)
   // or... go download json2.js and use that.

One other note… i’m using jsonp through jQuery so the data is returned as a string. Otherwise jQuery would have taken care of parsing it for me.


Leave a Reply

Your email address will not be published. Required fields are marked *