简体   繁体   中英

TypeError: Converting circular structure to JSON: Is there any way to ignore this warning?

I am trying to send a complex data structure composed of objects with arrays that have object with arrays that have object with arrays that may point to the first object, etc... and I get this error: TypeError: Converting circular structure to JSON which I completely understand why it happens.

I am trying to avoid flattening the structure as it will cost too much to process so I am wondering if there is any other way I can simply ignore this error when sending my http request(sending it to a PHP page)?

Nope. JSON is basically the right-hand-side of a JS assignment operation. You cannot build a self-referential JS structure in one line, eg:

var x = {y : x };

will simply spit out an "undefined" error for using x on the right-hand side before it was actually created on the left-hand side.

If you can't express something in a single line of JavaScript, then you can't express it in JSON.

You HAVE to split that circular structure somewhere.

Starting with PHP 5.4, there is an interface JsonSerializable available that allows objects to influence their json representation when being asked by json_encode() .

So you might be able to add this into your referenced object to only return the childs when asked for the first time. Or better, make those objects that reference this object NOT to return it, but everything else.

You may try and backport that interface to earlier versions of PHP, but you'd not only need that interface (which is easy), but also a replacement function for json_encode() that detects the presence of the interface and does all the handling stuff.

You could also try and implement a ->toJson() function in your objects that call each other recursively.

You probably have tried to suppress the error with @json_encode() , haven't you? It'll make the error go away, but not the pain with flattened circular structures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM