【问题标题】:Changing an objects value in JSON trough Node.js by editing the file通过编辑文件通过 Node.js 更改 JSON 中的对象值
【发布时间】:2018-12-14 20:58:27
【问题描述】:

我很难弄清楚如何在某个地方写作?我想写下 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
   });

【问题讨论】:

  • 不要投反对票,如果可以,请回答!我为此苦苦挣扎了几个小时并寻找答案。找不到任何可以解决我的问题的东西。我理解也许你们太优秀了,但这不是激励编码新手的方式。
  • 这可能会给你一些见解可能是stackoverflow.com/questions/10685998/…

标签: javascript arrays node.js telegram-bot


【解决方案1】:

您可以根据需要进行更新,如下所示:

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);

【讨论】:

  • 我不确定我是否理解。这如何更改 database.js 文件? ReadData.welcome_message[0] = "" 这不会更新它。下面的代码没有写任何新的东西,因为 Edited_ReadData 还没有定义?我错过了什么?
  • 所以我们在这里所做的就是在 ReadData 对象中加载 'database/.son' 的内容。然后我们修改字段 ReadData.welcome_message[0]。然后我们将结果写入“database.json”。我会稍微更新一下代码!
  • 所以现在我在写入 database.json 文件之前记录更新的 JSON。
  • 我很抱歉。这是解决此问题的正确方法。我只是不明白,我仍然不诚实。但是只要我的代码有效,如果我在脑海中定义了这个有效,就不需要理解它:) 非常感谢您的回复。
  • 其实并不难,只关注每一行的作用。你会学得很快!!
猜你喜欢
  • 2016-03-01
  • 1970-01-01
  • 2014-10-08
  • 2012-03-01
  • 2011-04-17
  • 2012-05-27
  • 1970-01-01
相关资源
最近更新 更多