gpt4 book ai didi

javascript - 通过编辑文件通过 Node.js 更改 JSON 中的对象值

转载 作者:行者123 更新时间:2023-11-30 20:23:24 29 4
gpt4 key购买 nike

我很难弄清楚如何在某个地方写字?我想写在 ReadData.welcome_message[0] 这个命令指出的地方。

我的 database.json 文件有这个;

{"faqs":["Birkere bir?","bir"],"welcome_message": ["welcome"]}

并且ReadData.welcome_message[0]指出welcome

    const fs = require('fs'); //imports node.js FileSystem
const ReadDatabase = fs.readFileSync('database.json'); //reads the file in synchronized way
const ReadData = JSON.parse(ReadDatabase); //parses bits so it can be readable

//These three for me to understand what is where
console.log(ReadData.faqs[0]);
console.log(Object.keys(ReadData));
console.log(ReadData.welcome_message[0]);


let edited_welcome = JSON.stringify(edited_message);
fs.writeFileSync('database.json', edited_welcome)//I understand this is the way to write to the file
//console.log('"' +edited_message + '"'); //did help me understand if my code worked
});

最佳答案

您可以根据需要像这样更新:

const ReadDatabase = fs.readFileSync('database.json'); //reads the file in synchronized way
const ReadData = JSON.parse(ReadDatabase); //parses bits so it can be readable

//These three for me to understand what is where
console.log(ReadData.faqs[0]);
console.log(Object.keys(ReadData));
console.log(ReadData.welcome_message[0]);

ReadData.welcome_message[0] = 'New Welcome Message'; // Modify as you need!

let edited_ReadData = JSON.stringify(ReadData);
console.log('Updated database.json: ', edited_ReadData);
fs.writeFileSync('database.json', edited_ReadData);

关于javascript - 通过编辑文件通过 Node.js 更改 JSON 中的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51207196/

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