Parsing a JSON string results in an 'Invalid Label' error
Heads up! This post was written in 2008, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.
$.post both process JSON easily, so it's my data type of choice.
Sometimes, however, I can't rely on
$.post to do the dirty work for me. One example is when I'm using a hidden
iframe to upload a file via "AJAX". To do this, the form posts the file to a server-side script. The script loads in the hidden
iframe, so users don't see what's happening behind the scene. Once the upload is complete, the script outputs some information about the file to the
For the sake of consistency, my server-side script always outputs a valid JSON string. I rely on this data, which gets scooped out of the
iframe, to tell me if the file got uploaded successfully and, if not, what the error was. If so, I need to know the filename, size, and location. What ends up in the
iframe usually looks something like this:
invalid label error.
The error is the result of
eval() interpreting the first item in the string as a label. This gets me everytime, but it's extremely easy to fix. Simply wrap the JSON string in parenthesis within
var response = eval('(' + jsonString + ')');