Node.js 如何更改json文件中字符串中的值?
我正在尝试更改JSON文件中字符串的值,但它的工作方式与我需要的不一样 JSON文件示例:Node.js 如何更改json文件中字符串中的值?,node.js,fs,Node.js,Fs,我正在尝试更改JSON文件中字符串的值,但它的工作方式与我需要的不一样 JSON文件示例: {'user1':{"name":"example","age":32,"coins":16}} 我试着用这个: let fs = require('fs') let file = fs.readFileSync('./example.json','utf-8') file.user1.name = "exampl
{'user1':{"name":"example","age":32,"coins":16}}
我试着用这个:
let fs = require('fs')
let file = fs.readFileSync('./example.json','utf-8')
file.user1.name = "example example"
fs.writeFileSync('./example.json',JSON.stringify(file,null,1))
它不会返回任何错误,但会将JSON文件保留如下内容:
{'user1':{'name':'example','age':32,'coins':16}},
"name": "example example"
}
}
这个JSON文件会更新discord中的每条消息
(是的,这适用于discord bot^^)您应该使用
require
加载json模块,因为它会自动解析json:
const fs = require('fs')
const file = require('./example.json');
file.user1.name = "example example";
fs.writeFileSync('./example.json',JSON.stringify(file,null,1))