How do I solve this Javascript error when converti

2019-05-06 18:18发布

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

3条回答
我想做一个坏孩纸
2楼-- · 2019-05-06 18:33

I would look at the following

html: HTMLDivElement should probably take the html of the element and not the element itself

or the following

Object -> proto -> Object -> proto -> Object -> ........

查看更多
迷人小祖宗
3楼-- · 2019-05-06 18:36

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.

查看更多
可以哭但决不认输i
4楼-- · 2019-05-06 18:43

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.

查看更多
登录 后发表回答