NodeJS writefilesync不将所有变量写入json文件

aiqt4smr  于 2023-02-12  发布在  Node.js
关注(0)|答案(1)|浏览(92)

我有这个代码:

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

我希望将下一个输出写入文件:

{
  "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":{}
      }

但这是我得到的

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

请注意字符串在"resume"之后是如何截断的,就像它无法读取变量fighter1fighter2一样,尽管它可以在第一次迭代中读取变量fighter1fighter2
为什么会这样?
谢谢你。

7kqas0il

7kqas0il1#

它跳过inturnoutturn,因为circular函数的工作方式不同。当该函数遇到fighter1属性时,它会将fighter1对象添加到seen WeakSet。然后,当它到达inturn属性时,该属性也指向同一个fighter1对象。它会发现对象已经在弱集中了,所以跳过了它,所以它做的正是你让它做的.
如果你希望它再次输出该对象的另一个副本,那么你将不得不改变你的circular()代码的工作方式,这样它就不会跳过同一个对象。记住,仅仅因为对同一个对象的引用在结构中出现了不止一次,就不是循环的。只有当对objA的引用在objA内部时,它才是循环的。所以,这不是设置circular()函数检测内容。
为了调试这一点,我添加了一系列日志记录,并使所有内容独立,如下所示:

const circular = () => { //fix circular stuff for json.stringify
    console.log(`creating seen`);
    const seen = new WeakSet();
    return (key, value) => {
        console.log(`checking "${key}"`, value);
        if (typeof value === 'object' && value !== null) {
            if (seen.has(value)) {
                console.log(`skipping "${key}"`);
                return;
            }
            console.log(`adding "${key}"`);
            seen.add(value);
        }
        return value;
    };
};

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

const all = { gameon: gameon, fighter1: fighter1, fighter2: fighter2, resume: resume, inturn: fighter1, outturn: fighter2 };

const result = JSON.stringify(all, circular());
console.log(result);

在您提供的示例中,没有任何内容是循环的,因此您只需完全删除circular()参数,就可以获得所需的输出。

相关问题