I need a function building a JSON valid string from any argument but :
- avoiding recursivity problem by not adding objects twice
- avoiding call stack size problem by truncating past a given depth
Generally it should be able to process big objects, at the cost of truncating them.
As reference, this code fails :
var json = JSON.stringify(window);
Avoiding recursivity problem is simple enough :
var seen = [];
return JSON.stringify(o, function(_, value) {
if (typeof value === 'object' && value !== null) {
if (seen.indexOf(value) !== -1) return;
else seen.push(value);
}
return value;
});
But for now, apart copying and changing Douglas Crockford's code to keep track of the depth, I didn't find any way to avoid stack overflow on very deep objects like window
or any event
. Is there a simple solution ?