I'm terrible at explaining in words, so I'll show and explain whats happening and what I would like to have instead, as clearly as possible.
Current code in node.js: - This opens and overwrites a .json file, this works properly, so far so good.
fs.open(fileName, "r", function(err, fd) {
if(!err) {
let file = require(fileName);
if(!file.created) {
file.created = {};
file.created.timestamp = "123456789";
let member_id = "456";
file.member_id = {};
file.member_id.text = "hello!";
}
fs.writeFile(fileName, JSON.stringify(file, null, "\t"), function (err) {
if(err) return console.log(err);
console.log("added to " + fileName);
});
return;
}
else
return console.log("woops, something went wrong.....");
});
Content of .json file:
{
"created": {
"timestamp": "123456789"
},
"member_id": {
"text": "hello!"
}
}
So it's opening and overwriting the .json file properly. That's great. The problem with this is; it adds a key named "member_id", while I want it to be "456" (see example below, I've added a //comment with an <--- arrow pointing it out)
Content of how I would like the .json file to be:
{
"created": {
"timestamp": "123456789"
},
"456": { // < ---------------------
"text": "hello!"
}
}
How can I make that possible? I cannot seem to figure it out at all...
Change this:
file.member_id = {};
file.member_id.text = "hello!";
to this:
file[member_id] = {};
file[member_id].text = "hello!";
And, any other references to that same property.
When you want to use a variable name as a property name, you must refer to it with the bracket syntax. file.member_id just means to reference a property named member_id as you can see in your current result. Putting it in brackets as in file[member_id] tells the interpreter to get the contents of the member_id variable and use that as a property name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With