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 ?
I did what I initially feared I’ll have to do : I took Crockford’s code and modified it for my needs. Now it builds JSON but handles
In case anybody needs it, I made a GitHub repository : JSON.prune on GitHub
Here is the code :
An example of what can be done :
Note: Contrary to the code in this answer, the GitHub repository is updated when needed (documentation, compatibility, use as module in commonjs or node, specific serializations, etc.). It’s a good idea to start from the repository if you need this pruning feature.