0

I have this code:

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;
  };
};

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};
    
fs.writeFileSync(file,JSON.stringify(all,circular()),{encoding:'utf8',flag:'w'}); 

I expect to have the next output written to file:

{
  "gameon":1,
  "fighter1":{
    "userid":"97",
    "username":"john",
    "items": {},
    "ailments":{}
   },
   "fighter2":{
     "userid":"91",
     "username":"james",
     "items":{},
     "ailments":{}
    },
    "resume":"",
    "inturn":{
      "userid":"97",
      "username":"john",
      "items":{},
      "ailments":{}
     },
     "outturn":{
       "userid":"91",
       "username":"james",
       "items":{},
       "ailments":{}
      }

but this is what I get instead:

{
  "gameon":1,
  "fighter1":{
    "userid":"97",
    "username":"john",
    "items":{},
    "ailments":{}
  },
  "fighter2":{
    "userid":"91",
    "username":"james",
    "items":{},
    "ailments":{}
   },
   "resume":""
 }

Please notice how the string truncates after "resume" like it couldn't read the variables fighter1 and fighter2 despite it could do it for the first iteration.

Why is that?

Thank you.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Cain Nuke
  • 2,843
  • 5
  • 42
  • 65
  • The `fighter1` and `fighter2` variables have been seen before, so the circular logic removes it. – Matt Feb 09 '23 at 00:41
  • But I dont want to do that. I need them there. Thats the whole point of the question. – Cain Nuke Feb 09 '23 at 00:45
  • If you're actually getting that circular reference error, then you're using data that is not shown in your question (not reproducible) because what you show does not contain circular references, so there's nothing I can do to help you with that. I've said what I can say. I'll be dropping out now and deleted my answer since it's apparently not what you want. – jfriend00 Feb 11 '23 at 19:53
  • And, to recap the main point that was in my (now-deleted) answer is that your `circular()` function detects duplicate objects in the object you're trying to serialize (some of which are not actually circular references and do not actually cause problems). It detects lots of false positives. – jfriend00 Feb 11 '23 at 19:56

0 Answers0