首页 > 解决方案 > 为什么它在保存的文件中添加反斜杠?

问题描述

我有一些代码应该已经在 .json 文件中保存了一个单词和其他单词,它有点完成这项工作,它将文件(fs.readFileSync)作为常量读取,当使用 fs.WriteFileSync 保存时它只是随机放置' s 在这样的文本中在此处输入图像描述

我不知道它为什么这样做,但它真的很烦人(readBl 是一个读取它并将它保存为变量的函数,所以当我想要它时,我可以用命令让它读取它,我知道我可以做到以其他方式,但 IDC)我的代码:

if(msg.content.startsWith('-addconf '))
  {
    var newword = msg.content.slice(9);

    if(blacklisted.includes(newword))
      return msg.channel.sendMessage("This word has already been blacklisted.")

    let rawdata = fs.readFileSync('blacklist.json');
    let rawRead = JSON.parse(rawdata);

    const str = JSON.stringify(rawRead);

    const str1 = str.replace('}', '');
    const str2 = str1.replace('{"blacklist":', '');
    //const str3 = str2.replace('""', '');

    let balance = {
    blacklist: str2 + newword
    };

    let data = JSON.stringify(balance);
    fs.writeFileSync('blacklist.json', data);

    readBl();
    msg.channel.sendMessage("Added a blacklisted word, test it out.")
}

标签: javascriptjsondiscorddiscord.jsfs

解决方案


A JSON value (like the keys) is enclosed in double quotes.

{ "someKey": "someValue" } 

So, how do you write a value that has quotes in it, like some"Value"With"Quotes"In"It? And you could have much much worse here...

(and more importantly, how does a JSON parser should read back such a value?

Is the value some? Is this a syntax error?

In JSON, like in many other contexts where you need to have delimiters, we need to have a way to tell that the quote " is not the syntax element to end the value, but some character that is part of the value.

The solution: escaping

So we do what is called "escaping" the character. In JSON (and in other languages), the escaping is done by prefixing with a backslash \.

And... since backslash is now a special character as well, that is used for escaping another character, you have the same problem again: how to represent a actual backslash in the value itself?

Simple, same solution: you escape the backslash itself.

So, when saving a JSON string value:

  • quotes " become \";
  • backslashes \ become \\.

How to read that back?

Any functioning JSON reader will read that properly, it's the correct way to serialize those characters, so you don't have any issue here!


推荐阅读