javascript - 为什么它在保存的文件中添加反斜杠?
问题描述
我有一些代码应该已经在 .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.")
}
解决方案
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!
推荐阅读
- mysql - 我有一个问题 BCRYPT 与 NodeJs 比较比较 Mysql 数据库中的密码
- database - 组件“DEPARTMENT_ID”必须声明为 PLSQL
- php - 如何使用不同的发件人地址从 php laravel 应用程序发送电子邮件
- ansible - 如何使输入与ansible中的问题在同一行?
- php - PHP脚本没有收到我使用Jquery通过AJAX发送给它的文件
- c# - 如何从 ODataPrimitiveSerializer 获取属性信息
- amazon-web-services - 使用 CI/CD 管道将 PHP 应用程序从 Azure DevOps 部署到 AWS
- regex - 正则表达式仅匹配 URL 中的特定参数
- java - 如何使用 elastic-apm-agent 创建的所有详细信息创建自定义跨度?
- docusignapi - 任何用户都可以编辑 DocuSign 信封