如何正确存储相互引用的对象?(圆形结构)



如果我有类似的东西

let a = {};
let b = {pointingTo: a},
a.pointingTo = b

那么有可能以某种方式将其存储在.json文件中吗?

不,因为您无法将循环结构转换为JSON字符串

但这里有一些你可以做的

let a = {a:1};
let b = {pointingTo: a,b:2};
a.pointingTo = JSON.parse(JSON.stringify(b));

输出应该是{"a":1,"pointingTo":{"pointingTo":{"a":1},"b":2}}然后您可以字符串化并将其保存在JSON文件中

使用node.js

require('fs').writeFileSync('file.json', JSON.stringify(a));

使用浏览器

function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
download('file.json', JSON.stringify(a))

第S页:要进行缩进,只需要JSON.stringify(a, null, 2)

如果这个javascript是客户端的,那么你必须将它存储在本地存储中,如果它是服务器端的javascript,我不明白为什么它不可能。它基本上是MongoDB的一个非常简化的版本。

最新更新