Js circular reference problem

var b = {
    
}
var a = {
    b: b
}
b.a = a
JSON.stringify(b) // bstringifyb
< H1 > ask everyone for advice! < / H1 >

question add:
is a colleague"s question, he encountered in node development problems:
to print some built-in objects of a library, but the expansion is too large, and then use stringify, and then report these errors. What is needed is a solution to this scenario.

Nov.26,2021

there is a way to directly remove attributes in objects that involve circular references. A json extension package has done this for us. Just use it directly. The link is as follows:

JSON.decycle removes circular references
JSON.retrocycle restore

    var b = {
}
var a = {
    b: b
}
b.a = a
var c=JSON.decycle(b)
console.log(JSON.stringify(c))
console.log(JSON.retrocycle(c))

result:

{"a":{"b":{"$ref":"$"}}}

is sure to report an error. You have been quoting each other all the time, and objects are assigned endlessly. If you try to see what b is, you will know why it was misreported.


JSON.stringify itself does not support circular references.

executing this method on objects that contain circular references (objects refer to each other to form an infinite loop) throws an error.

can you understand if you look at this picture?

stringify wants to output the JSON string of the entire object
because of the circular reference, it can't end at all


  

the string referenced by the loop is infinitely long. How can you stringify, console.log

directly?
Menu