Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I solve this Javascript error when converting JSON to string?

Uncaught TypeError: Converting circular structure to JSON

The object I'm trying to stringify is this (I logged it in javascript console):

Object
GsearchResultClass: "GlocalSearch"
accuracy: "8"
addressLines: Array[2]
city: "Cupertino"
content: ""
country: "United States"
ddUrl: "http://www.google.com/maps?source=uds&daddr=10825+North+Wolfe+Road,+Cupertino,+CA+(Southland+Flavor+…"
ddUrlFromHere: "http://www.google.com/maps?source=uds&saddr=10825+North+Wolfe+Road,+Cupertino,+CA+(Southland+Flavor+…"
ddUrlToHere: "http://www.google.com/maps?source=uds&daddr=10825+North+Wolfe+Road,+Cupertino,+CA+(Southland+Flavor+…"
html: HTMLDivElement
lat: "37.335405"
listingType: "local"
lng: "-122.015386"
maxAge: 604800
phoneNumbers: Array[1]
region: "CA"
staticMapUrl: "http://maps.google.com/maps/api/staticmap?maptype=roadmap&format=gif&sensor=false&size=150x100&zoom=…"
streetAddress: "10825 North Wolfe Road"
title: "Southland Flavor Cafe"
titleNoFormatting: "Southland Flavor Cafe"
url: "http://www.google.com/maps/place?source=uds&q=stinky&cid=9384294304761453216"
viewportmode: "computed"
__proto__: Object

And I'm doing it like this:

JSON.stringify(theobject);
like image 353
TIMEX Avatar asked Jan 20 '23 13:01

TIMEX


2 Answers

An object is referencing itself somewhere; hence the message "circular structure." I suspect it might be in the HTMLDivElement. Are you using this only for debugging purposes or do you actually want to do something meaningful with this JSON? If you're just using it for debugging, most modern JavaScript debuggers will let you just log an object to the console. If you're actually trying to do something with the data, you should pull out only the things you need from this object and put them into a new trimmed down object that you can pass to JSON.stringify. This object looks like it came from a Google API and has lots of extra data in it.

If you don't mind destructively modifying the object, try selectively nulling out suspicious fields and see if JSON.stringify will accept the object. At least that way you'll know what's causing it. Note that if you do this you may end up breaking the object for any future uses.

like image 104
nss Avatar answered Jan 29 '23 20:01

nss


Had this same problem, turns out I was an idiot and forgot the .val() at the end of the element that I wanted to insert into the JSON object.

Be sure you're not shoving a whole element into the JSON object, otherwise it will attempt to JSON encode something that is not valid JSON.

like image 31
John Paul Barbagallo Avatar answered Jan 29 '23 21:01

John Paul Barbagallo