我有一个问题,如何在Braces/{}中设置json代码?
下面的所有代码都解释了我需要做的事情
我想做这个登录系统,如果我有任何错误,我很抱歉
看上去像那样
{
"test": "test",
"test1": "test1"
}我的密码
var usac = JSON.stringify({username: newusername, password: newpassword }, null, 2)
fs.appendFile('account.json', usac, fin)
function fin(err){
console.log("done")
}我的json代码
{
"username": "test",
"password": "test"
}{
"username": "test1",
"password": "test1"
}{
"username": "test2",
"password": "test2"
}{
"username": "test3",
"password": "test3"
}{
"username": "test4",
"password": "test"
}我想要代码是对的
{
"user" :{
"username": "test",
"password": "test"
}
"user1" :{
"username": "test1",
"password": "test1"
}
"user2" :{
"username": "test2",
"password": "test2"
}
"user3" :{
"username": "test3",
"password": "test3"
}
"user4" :{
"username": "test4",
"password": "test4"
}
}发布于 2022-10-08 10:01:59
您正在附加到一个json文件。但是,内容并不是json。
一个快速解决办法是:
value.
{}作为初始内容的文件。
username作为密钥& account对象为,JavaScript H 215G 216相同的文件const fs = require('fs');
class AccountsInterface {
constructor(filePath) {
this.filePath = filePath;
}
getAll(callback) {
fs.readFile(this.filePath, function onReadComplete(error, content) {
if(error) {
return callback(error);
}
const accountsMap = JSON.parse(content.toString());
callback(null, accountsMap);
});
}
addAccount(account, callback) {
const self = this;
self.getAll(function onAccountsLoaded(error, accountsMap) {
if(error) { return callback(error); }
accountsMap[account.username] = account;
const accountsMapString = JSON.stringify(accountsMap);
fs.writeFile(self.filePath, accountsMapString, function onWriteComplete(error) {
if(error) { return callback(error); }
callback();
});
});
}
// Async version
async getAllAsync() {
const content = await fs.promises.readFile(this.filePath);
const accountsMap = JSON.parse(content.toString());
return accountsMap;
}
async addAccountAsync(account) {
const accountsMap = await this.getAllAsync();
accountsMap[account.username] = account;
const accountsMapString = JSON.stringify(accountsMap);
await fs.promises.writeFile(this.filePath, accountsMapString);
}
}
// Ensure this file's contents are `{}` in the beginning
const accountsFilePath = './accounts.json';
const accountsInterface = new AccountsInterface(accountsFilePath);
const account = { username: 'test', password: 'test'};
accountsInterface.addAccount(account, onAccountAdded);
function onAccountAdded(error) {
if(error) { return console.log(error); }
// here, the accounts file will look like {"test": {"username": "test", "password": "test"}}
}
// Async version
const account = { username: 'test2', password: 'test2'};
await accountsInterface.addAccountAsync(account);
// here, the accounts file will look like {"test": {"username": "test", "password": "test"}, "test2": {"username": "test2", "password": "test2"}}https://stackoverflow.com/questions/73994080
复制相似问题