I wanted to try to develop my own database with JS and Json. Unfortunately, I run into problems there.
How do I read specific content from the Json file I googled and got this:
fs.readFile('./databases/' dbName ".json", (err, data) => {
if (err) throw err;
content = JSON.parse(data);
console.log(content)
});
But then I only get this output
{
members: [
{ Username: 'User-1', Password: 'lol' },
{ Username: 'User-2', Password: 'lol' }
]
}
Process finished with exit code 0
and not a specific one, for example just the password of user-1 from the json file:
{
"members": [
{
"Username": "User-1",
"Password": "lol"
},
{
"Username": "User-2",
"Password": "lol"
}
]
}
(I really only want to use json files for this project)
Thanks for helping :)
CodePudding user response:
your question does not have much informations
fs.readFile("./databases/" dbName ".json", (err, data) => {
if (err) throw err;
var username = "User-1";
var password = "lol";
for (var i = 0; i < content.members.length; i ) {
if (
content.members[i].Username == username &&
content.members[i].Password == password
) {
console.log("Login Successful");
return true;
}
}
console.log("Login Failed");
return false;
});
get the username and password fields from user side and use the for loop to validate the values are in the json database file
CodePudding user response:
As for storing data in a JSON-like object, databases already exist that offer great storage options out there for example MongoDB or Firebase.
As for your problem, the code is operating correctly what your looking for is a filter
fs.readFile('./databases/' dbName ".json", (err, data) => {
if (err) throw err;
const username = username;
const password = password;
//const username = "User-2";
//const password = "lol";
content = JSON.parse(data);
console.log(content.members.filter(mem => { if (mem.Username === username && mem.Password === password) return mem} ));
});
This will return:
[ { Username: 'User-2', Password: 'lol' } ]
You'll have you include a way to accept the username and password or any other filter variables you can think of.