Saturday, September 1, 2018

javascript - How can I print a circular structure in a JSON-like format?



I have a big object I want to convert to JSON and send. However it has circular structure. I want to toss whatever circular references exist and send whatever can be stringified. How do I do that?



Thanks.



var obj = {
a: "foo",
b: obj
}


I want to stringify obj into:



{"a":"foo"}

Answer



Use JSON.stringify with a custom replacer. For example:



// Demo: Circular reference
var circ = {};
circ.circ = circ;

// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(circ, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Duplicate reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null; // Enable garbage collection


The replacer in this example is not 100% correct (depending on your definition of "duplicate"). In the following case, a value is discarded:



var a = {b:1}
var o = {};
o.one = a;
o.two = a;
// one and two point to the same object, but two is discarded:
JSON.stringify(o, ...);


But the concept stands: Use a custom replacer, and keep track of the parsed object values.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...