Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at cf.Objective() 2012 (Minneapolis, MN) with:

JSON: Minor But VERY Important Detail Creating Syntax Error: Invalid Label

By Ben Nadel on

I was beating my head against the wall today for a bit trying to figure out why some values coming back from my ColdFusion JSON-esque solution where not evaluation properly. I had the following code in my AJAX data handler:

  • this.OnLoad(
  • eval( this.Connection.responseText );
  • );

Damn thing was driving me crazy. Kept all kinds of errors like invalid label name and what not (I don't remember then very well as the head-bashing pretty much cleared those brain cells). Then, suddenly I saw the mistake: I forgot my parentheses:

  • this.OnLoad(
  • eval( "(" + this.Connection.responseText + ")" );
  • );

To be honest, I am not sure what exactly the difference is. The parens must help Javascript figure out how and what it is evaluating. Maybe I will figure it out in my next book: Javascript Bible.




Reader Comments

Thanks for the tip, I faced exactly the same problem.
Dunno what the parenthesis do change, either.

Reply to this Comment

Anything I can do to help :) I am just recently getting into this stuff, so hopefully I will understand what that means eventually.

Reply to this Comment

dude, THANK YOU! I think you're the only guy on the web that wrote about this.
Love the "de-spam" feature here :)

Reply to this Comment

Thanks Ryan! Glad to help. Thanks also for the de-spamming props. I got so tired of reading those words behind wavey lines that I needed something simple. So far it seems to work perfectly. I get a good number of bots hitting the comments page, but nothing slips through.

Reply to this Comment

Thanks a lot!

This seems like an extremely common error and yet I had to page through several result pages from Google to get to a website that dealt with it directly.

I guess the error lies in that eval tries to interpret, say, {"kinky":"you got that right"} as a label (which are a pretty obscure JS feature - http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Loop_Statements:label_Statement).
In fact, if you try running <script>{"kinky":"you got that right"}</script> it will also die. So when you add the parentheses you seem to make the statement unambiguous an object to JS.

And looking at Crockford's JSON in Javascript page (http://www.json.org/js.html) I noticed he does include the parentheses in his example:

var myObject = eval('(' + myJSONtext + ')');

But I still think he should point it out in huge bold letters (^_^), it's nonobvious and critical--I'm sending him an email. :)

Anyway, thanks again, you saved me much head-scratching.

Reply to this Comment

TV,

Wicked sweeet. Always glad to help. Please contact me if you have any other issues that are stumping you.

Reply to this Comment

You have no idea how badly /I/ was hitting my head against the wall. I'm glad it's over now. Thanks!

Reply to this Comment

This page is now top Google hit for "json invalid label". Exactly what I needed - so let me add my thanks to the thousands of others

Reply to this Comment

Thanks Ben,
Although I was blessed and didn't have to bang by head as there was google and Your post is #1 on "SyntaxError: invalid label".
My body thanks You for skipped self-inflicted injuries. :)

Reply to this Comment

critical.
non obvious.
you just saved me about a day of brainache!

!!Thank You!!

Reply to this Comment

Just want to add my "you saved some hours of my life" thank you :)
would be interesting to know why the parenthesis are necessary though. But at least now I know that they are.

Reply to this Comment

I managed to create this error in another way:

foo = new Object();
foo.bar = 'foo':

(Note the colon, instead of a sem-colon.)

Drove me almost nutcase.

Reply to this Comment

i still get that weird error with dojo from today's svn snapshot:

here's the code in question:

function onclick_myButton()
{
var bindArgs = {
url: "{{ verify_url }}",
mimetype: 'text/javascript',
error: function(type, errObj, evt){
// handle error here
alert('Try again Dude!');
},
load: function(type, data, evt){
// handle successful response here
var jsonObj = eval( '(' + data + ')' );
// myElement = document.getElementById('helloworld');
// myElement.childNodes[0].nodeValue = jsonObj;
// myElement.innerHTML = data;
alert(jsonObj);
},
// might get deprecated in a future release
formNode: document.getElementById("myForm")
};
dojo.io.bind(bindArgs);

... which outputs the following in firebug:

DEBUG: [SyntaxError: invalid label, file: http://localhost:8000/media/js/dojo/dojo.js, line: 114]
...

if i use dojo.json.evalJSON(data) i get similar results, as the
type == error gets defined..

any ideas?

Reply to this Comment

Erob,

Sorry, I am not familiar with Dojo. I think that is one of the tradeoffs with using a Javascript framework - its hard to debug where the heck stuff is going wrong. But, looking at the code you posted, I cannot see anything wrong.

Reply to this Comment

If the parenthases are vital to the json being eval'd "correctly" then why aren't they included from the server side?

Is it simply for the obscure case where you actualy do send back a label?

In my work, I have included the paranthases in the xslt that creates the json from xml.

Reply to this Comment

Stuart,

You ask the tough questions :) I cannot think of any reason why I would not use the parens... so to that effect, I cannot think of a situation where it would be bad to include them on the server side.

The only thing I can think of is a separation of concerns. Meaning, JSON doesn't care what you do with it. The Parens are only for use during evaluation of the JSON data. JSON is just a style of notation and syntax - we just happen to be using it for AJAX and dynamic evaluation.

But other than that, can't think of an argument against what you are saying.

Reply to this Comment

Thank you -- I was only starting to get frustrated with this when I did a google search on 'javascript "invalid label"', and you were the first result. The fix worked perfectly. Many thanks!

Reply to this Comment

Hope you will stay for a long time number one on "json invalid label" in Google; -)

Thanks !

Reply to this Comment

Here is a sampel of the JSON text being returned from an httpRequest

{"Results":
{"pubNeighborhhods":
{"Rows":[
{"intNeighborHoodID":1,"intBookID":1,"Name":"Blairgowrie","Latitude":"0","Longitude":"0","Country":"Australia","state":"Vic"}
,{"intNeighborHoodID":2,"intBookID":1,"Name":"Crib point","Latitude":"0","Longitude":"0","Country":"Australia","state":"Vic"}
,{"intNeighborHoodID":3,"intBookID":1,"Name":"Moorooduc","Latitude":"0","Longitude":"0","Country":"Australia","state":"Vic"}
]
}
}
}

the above is returned as one long string with no line breaks, i added those for readability

when i use eval() it causes "invalid label" error

I have read about this online and the only answer i find is to enclose the JSON string in parentheses "(" and ")"

when i do this i get the following error
"missing ) in parenthetical"

i have not found a solution to this issue although i have found a couple posts asking about it

thanks

bud

Reply to this Comment

@Bud,

It works fine for me:

<cfsavecontent variable="strJSON">
{"Results":{"p............state":"Vic"}]}}}
</cfsavecontent>

<html>
<head>
<title>JSON Test</title>

<script type="text/javascript">

var data = eval(
"(" +
"#JSStringFormat( Trim( strJSON ) )#" +
")"
);

alert( data.Results );

</script>
</head>
<body>
</body>
</html>

I took out all the line breaks and white space from your JSON data. Maybe that is what was causing the problem.

Reply to this Comment

thanks for looking at it. i may never now what I had messed up but when i took it off my local development serve, i got it to work. i shut down my development computer and restarted.

i was getting the error while running it through a debugger.

the short answer is that it works for me too now with no change in the sorce code??? got to love the .net development envornment...

thanks for the response.

bud

Reply to this Comment

Thanks! Just got done beating my head into the wall thinking my JSON syntax was hosed.

Your solution worked for me also!!!!

Reply to this Comment

I spent a good deal of time tracking down this issue. Thanks for your tremendously useful post!

You'll be happy to know (if you don't already, which you probably do) that the your page is now the #1 spot on Google for the key words "json invalid label" and even "invalid label". ;)

Reply to this Comment

Thanks dude you saved me some headaches :)
There was a lot of errors with IE on pages where I didn't include those parenthesis... Adding those fixed them.

Reply to this Comment

I was just about to start my own personal head bashing session when I decided to do a simple search. This page came up first and saved me a couple of hours of headache.

Thanks!

Reply to this Comment

Thanks! I was definitely having a "WTF is PC Load Letter?!" moment with the "invalid label" error.

Reply to this Comment

In addition to thanking the author, I'd like to thank all the posts here for the refreshing blast of positivity ;)

Reply to this Comment

Almost two years later and this post is still paying dividends. Luckily I didn't bang my head for too long before googling "invalid label". Thanks Ben!

Reply to this Comment

if it executes javascript code the eval command wouldnt throw a hissy fit, the problem results when responseText is an object without assignment, anonymous objects require encapsulation with curly braces on instantiation.

if however you don't want to use curly braces this would work too, responseText Object gets assigned to someVar

eval('someVar = '+responseText')

Reply to this Comment

Dude, your solution worked for me. I was pulling my hair out! Thanks a lot for posting this.

Reply to this Comment

though i think every thinnk is resolvedfor this - but let me know if i can eb of some help. i have done few of tutorials on this , may be a little help i can follow

Reply to this Comment

Add my name to the thousands of grateful developers who's been beating his head on the wall! What gets me, is that it has been working perfectly fine for *days* without the parens. Now, suddenly, it requires the parens. Perhaps a tiny, subtle difference in the data made the difference between working and not working.

Reply to this Comment

Over 2 years on and still helping people with this.
Thanks for posting it.

Reply to this Comment

Hi ,
I am getting this JSON object from my code ( a servlet)
[{"name_one": "select_one","value_one": -1}]

I am syntax error when I send this as arg in my callback function..

$.getJSON(
getThis().baseURL()+"citiesForWidget.htm?format=json&_jsoncallback=?",
function(data){
alert(data);
});

Any idea ??

Reply to this Comment

@Sriram,

I am not seeing anything suspicious in your code. Can you check the actual return value via FireBug to see what value is coming through in the SCRIPT tag.

Reply to this Comment

This really saved my ass last night.

You're still the Google number 1 on this issue.
Thanks loads.

Reply to this Comment

>>> eval( { "an":"object" } );
Object an=object

>>> eval( '{ "an":"object" }' );
SyntaxError: invalid label

>>> eval( '({ "an":"object" })' );
Object an=object

wtf, right?

Reply to this Comment

@Dan,

I think it's that the addition of the parenthesis turns it into a expression. You can't evaluate an object in a string, but you can evaluate an expression held in a string.

But, it's a bit fuzzy for me as to what's really going on.

Reply to this Comment

Thanks for the information. You are the top result on Google for: javascript "invalid label". I would have spent a lot more time and probably never thought to try this "solution" myself. Appreciate you sharing the information.

Reply to this Comment

You sir, are my saviour... I had this problem and thanks to your advice I was able to solve it. Thank you!

Reply to this Comment

Thanks for the great tip. Probably just saved me hours of head bashing face palming...

Reply to this Comment

One more thank you - I caught this right before heading into a mess of json debugging... Thanks!

Reply to this Comment

My code:
alert(request.responseText);
//var data = [request.responseText];
var data = eval( "(" + request.responseText + ")" );
//var data = eval('(' + request.responseText + ')');
alert(data[1]);

When I alert the request.responseText.It would now report syntax error. I'm confused about it.

Reply to this Comment

Add me to the list! Still this whole setup seems pretty fragile to me. I wonder if TPTB would consider adding a parameter to CF's SerializeJSON() function to include brackets?

Reply to this Comment

Les Experts en récupération de données
Votre disque dur, disque dur ,raid, vient de tomber en panne ? Vos données ont disparu ? Chronodisk est là pour vous aider. Avec plus de 11.000 disques sauvés chaque année, nos experts sont les mieux placés pour récupérer vos données.

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.