In order to prevent that error regarding circular structure to JSON I have this function:
circular = () => { //fix circular stuff for json.stringify
seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
it works fairly well except in the case below:
var gameon = 1;
var fighter1 = {"userid":"97","username":"john","items":{},"ailments":{}};
var fighter2 = {"userid":"91","username":"james","items":{},"ailments":{}};
var resume = 30;
all = {"gameon":gameon,"fighter1":fighter1,"fighter2":fighter2,"resume":resume,"inturn":fighter1,"outturn":fighter2};
console.log(JSON.stringify(all,circular()));
it will print something like this:
{"gameon":1,"fighter1":{"userid":"97","username":"john","items":{},"ailments":{}},"fighter2":{"userid":"91","username":"james","items":{},"ailments":{}},"resume":30}"
Please notice how the output truncates after resume
.
If I don't use the circular function then I get the correct output but also the "circular structure" error if I try to write to a file.
Why is that?