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 Scotch On The Rocks (SOTR) 2011 (Edinburgh) 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

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

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

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.

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.

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

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. :)

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.

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.

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?

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.

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.

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.

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!

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

@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.

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

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". ;)

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!

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!

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')

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

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.

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 ??

@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.

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

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

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

wtf, right?

@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.

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.

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.

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?

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.