JSON: Minor But VERY Important Detail Creating Syntax Error: Invalid Label
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.
Want to use code from this post? Check out the license.
Reader Comments
Thanks for the tip, I faced exactly the same problem.
Dunno what the parenthesis do change, either.
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.
Elzr, glad I could help :)
awesome, you rock! (that was driving me nuts)
Thanks you, saved me with this info.
TV,
Wicked sweeet. Always glad to help. Please contact me if you have any other issues that are stumping you.
You have no idea how badly /I/ was hitting my head against the wall. I'm glad it's over now. Thanks!
Wow, thank you for saving me a miserable night.
Thank you very much for the hint !
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
You are my hero!!!!
Thank you so much for posting this JSON "paren" issue.
:-)
Thank you thank you thank you!
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. :)
critical.
non obvious.
you just saved me about a day of brainache!
!!Thank You!!
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.
Till,
Thanks for the heads up on other ways to debug the erorr!
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!
Hope you will stay for a long time number one on "json invalid label" in Google; -)
Thanks !
lol. i think we found a little bug in your comment parser. =) see links above. thanks again.
thanks; this was really frustrating. :-)
Thanx it helped me too :)
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
Oh .NET.. You!!! Good to hear that it is working now.
You helped me too. good man. good man!
Thanks! Just got done beating my head into the wall thinking my JSON syntax was hosed.
Your solution worked for me also!!!!
Another satisfied customer. Not seeing "invalid label" was a beautiful thing.
wow - there is a solution for everything on the nets. :) thanks, man... this came in handy!
Thanks for writing this!
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". ;)
@Brian,
That's good to hear :) I am just glad that this is helping people!
Thanks! That is a brilliant insight and one that the Rhino book misses... ;)
Let me also just say thanks. For those interested in why this is happening, I found this explanation useful: http://www.thescripts.com/forum/post1989841-4.html.
Thanks dude:) that worked. This is crazy, I had a bit struggle.
save my day :-)
thanks for the tip
Wheee, thanks - saved me some head bashing :)
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.
That's what I like to hear - another head being saved :)
+1 from me, the same problem, solved in 5- mins thanks to this page.
i guess you saved me from a sleepless night!!
thanks a lot!
sincerely yours,
Sven Buschbeck
Thanks man!
Google-debugging is the best, but it wouldn't work without you.
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!
thanks for saving me a lot of wasted time :)
Thanks! I was definitely having a "WTF is PC Load Letter?!" moment with the "invalid label" error.
In addition to thanking the author, I'd like to thank all the posts here for the refreshing blast of positivity ;)
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')
Had to try the antispamthingy, dont see any yet though!
Thank you! Hilarious how long this post has lasted and remains useful...
Hey Man, i spent 4 hours on this - now its all working THX TO YOU!
lol you rock!
But why does this solve the problem. Why do we require parenthesis.
This tip works perfectly for me, too.
Thanks for my saved hours.
Wow, thanks a lot! This solved my problem!
This error started to drive me crazy...
Dude, your solution worked for me. I was pulling my hair out! Thanks a lot for posting this.
@Robin,
Glad to have helped.
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
Dude...after a day of beating my head on the wall, this was it. Thanks!!
thanks, your tip solved my problem
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.
@Gary,
As always, Im glad to have helped.
Over 2 years on and still helping people with this.
Thanks for posting it.
@Joe,
It's the gift that keeps on giving ;)
Thanks a lot!
thx man i had the same problem.......
Thanks a lot! I wouldn't have figured this out in a million years.
Wow, thanks for that! I feel like a moron now. ;)
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.
This really saved my ass last night.
You're still the Google number 1 on this issue.
Thanks loads.
man, you saved me from a whole night of head-bashing. THANKS!
>>> 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.
@Matt,
Awesome my man, glad this still is helping people.
thanks dude. that was cool.
You sir, are my saviour... I had this problem and thanks to your advice I was able to solve it. Thank you!
thanks, this helped me! you're first on google for this syntax error and i'm glad :)
Thanks for this great advice.
Thanks for the great tip. Probably just saved me hours of head bashing face palming...
after 4 years, this post is still helping people, including me! thanks man!
Funny, but it helps me :-)
Thanks!
This post never gets old - I love it :)
Thank's Ben.
This post is old but still useful :)
One more thank you - I caught this right before heading into a mess of json debugging... Thanks!
Yes, still useful. Thanks
Thanks Ben! Train hard!!
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.