Thursday, April 29, 2010

JSON eval problem "Error: invalid label"

The other day I created a web service receiving XHR (ajax) requests and returning JSON response.
The calling code eval'ed the JSON in order to use it as a JavaScript object, like this:

var ret_json = service.result; // AJAX response JSON string

var ret_json_obj = eval(ret_json); // ERROR
In IE I got error: "; expected" and in FF I got "Error: invalid label".

Solution was to wrap the ret_json with parenthesis and a string, like this:

var ret_json = service.result; // AJAX response JSON string

var ret_json_obj = eval("(" + ret_json + ")"); // WORKING

The text must be wrapped in parenthesis to avoid tripping on an ambiguity in JavaScript's syntax.

Read here more about JSON.

Cheers.

No comments: