尝试将循环结构转换为JSON时出现问题
尝试将循环结构转换为JSON时出现问题
这个问题已经有了相关答案:
为了防止出现循环结构对JSON的错误,我有这个函数:
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}; console.log(JSON.stringify(all,circular()));
它会打印出像这样的东西:
{"gameon":1,"fighter1":{"userid":"97","username":"john","items":{},"ailments":{}},"fighter2":{"userid":"91","username":"james","items":{},"ailments":{}},"resume":30}"
请注意在resume
后输出被截断的部分。
如果我不使用循环函数,那么我就可以得到正确的输出,但如果我尝试写入文件,我也会得到“循环结构”错误。
为什么会这样呢?
admin 更改状态以发布 2023年5月23日
你的 circular
函数对于任何已经见过的对象都返回 undefined。JSON.stringify() 遇到 undefined
就停止处理剩下的对象。你可以尝试修改你的函数,为循环引用添加一个占位符:
const circular = () => { let seen = new WeakSet(); let placeholder = {}; return (key, value) => { if (typeof value === 'object' && value !== null) { if (seen.has(value)) { return placeholder; } seen.add(value); } return value; }; };