Using Cordova and PhoneGap: Uncaught TypeError: Converting circular structure to JSON

cordova

For anyone testing out their Javascript application on Android using Cordova or PhoneGap, you’ll probably run into this error.
(If you’re debugging using the chrome developer tools).

For some reason it seems to add HTMLElements onto your Javascript objects…. Which become apparent when you try to use JSON to stringify them.

I finally found the solution for getting rid of it at: https://stackoverflow.com/questions/10392293/stringify-javascript-object-with-circular-reference/22104400#22104400 (the last solution with 0 upvotes from Timmerz).

You just have to remove any HTMLElements that somehow were added to your javascript objects. Like so:

var an_object = {"language":"javascript", "sanity":"none"};
var json_string = JSON.stringify(DropClasses(an_object));
console.log(json_string);

var DropClasses = function(object)
{
for (var param in object)
{
if (object[param] instanceof jQuery || object[param] instanceof HTMLElement)
object[param] = null;
else if (typeof object[param] == 'object' )
DropClasses(object[param]);
}
return object;
}

Hope that helps other people out! I didn’t have any circular references/ objects referring to themselves as sub objects, and testing on Firefox and chrome confirmed that. But running on Android using Cordova caused the error to happen whenever I used JSON.stringify on any object. Not sure if it’s a webkit problem, or just the inconsistency of how javascript is compiled from browser to browser in general.

Having to use Javascript makes me miss Java so much XD

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *