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

标签 javascript arrays node.js telegram-bot

我不知道如何在某个地方书写?我想写下 ReadData.welcome_message[0] 这个命令指出的位置。

我的database.json文件有这个;

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

并且ReadData.welcome_message[0]指出欢迎

    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/

相关文章:

javascript - 令人头疼的 JS 范围和关闭

java - 如何将 Multiple 数组转换为 Json 数组并将 Json 添加到 hashmap

javascript - 单击时循环遍历数组

Java 可选包含数组

javascript - Node.js 奇怪的原型(prototype)继承

javascript - 所需的脚本可以停止其父脚本的执行吗?

javascript - 循环数组中的值

javascript - HTML5 本地存储(XML/JSON 数据)

javascript - 在 Cloud Firestore onCreate 触发器中运行批处理或事务

javascript - 将点击事件附加到 div 内的某些链接