gpt4 book ai didi

javascript - 将对象添加到 JSON

转载 作者:行者123 更新时间:2023-12-01 00:32:49 27 4
gpt4 key购买 nike

我有一个 settings.json 文件,其中包含以下数据(其中 123456789 是一个不同的用户 ID):

{
"123456789":
{"button_mode":true}
}

因此,我需要做的是将类似的 id: {button_mode: value} 对象推送到此 JSON 文件,以防当前用户的 ID 没有条目。我尝试使用 lcSettings.push() ,但显然它不起作用,因为我有一个对象,而不是数组。当我用方括号代替大括号使其成为数组时,我的代码根本不执行任何操作。这是它的一个片段(Node.js):

var lcSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
var currentUser = id;
if (lcSettings.hasOwnProperty(currentUser)) {
// in case settings.json contains current user's id check for button_mode state
if (lcSettings[currentUser].button_mode == true) {
// if button_mode is on
} else
if (lcSettings[currentUser].button_mode == false) {
// if button_mode is off
}
} else {
// in case there's no entry for current user's id
// here's where I need to push the object for new user.
}
fs.writeFileSync('./settings.json', JSON.stringify(lcSettings))

有人对如何实现有想法吗?任何帮助表示赞赏。

最佳答案

您可以使用bracket notation向对象添加动态属性:

lcSettings[id] = { button_mode: false };

您可能还想验证 settings.json 不为空,否则 JSON.parse() 将失败。在本例中,您可能希望将 lcSettings 初始化为空对象 (lcSettings = {}),以便上述内容有效。

关于javascript - 将对象添加到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58364252/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com