llgdd
llgdd

Reputation: 3

Add an object to JSON

I have a settings.json file that contains following data (where 123456789 is a distinct user id):

{
 "123456789":
   {"button_mode":true}
}

So what I need to do is push a similar id: {button_mode: value} object to this JSON file in case there's no entry for current user's id. I tried to use lcSettings.push() but obviously it did not work since I have an object, not an array. When I put square brackets instead of curly ones to make it an array, my code doesn't do anything at all. Here's a snippet of it (Node.js):

var lcSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
var currentUser = id;
if (lcSettings.hasOwnProperty(currentUser)) {
   // in case settings.json contains current user's id check for button_mode state
   if (lcSettings[currentUser].button_mode == true) {
      // if button_mode is on
   } else
   if (lcSettings[currentUser].button_mode == false) {
      // if button_mode is off
   }
} else {
   // in case there's no entry for current user's id
   // here's where I need to push the object for new user.
}
fs.writeFileSync('./settings.json', JSON.stringify(lcSettings))

Does anybody have ideas on how it can be implemented? Any help appreciated.

Upvotes: 0

Views: 61

Answers (2)

mohkamfer
mohkamfer

Reputation: 445

To 'push' elements to an object you simply define them, as in

object['123456789'] = { button_mode: true };

Upvotes: 1

Anthony
Anthony

Reputation: 6482

You can use bracket notation to add a dynamic property to an object:

lcSettings[id] = { button_mode: false };

You may also want to verify that settings.json is not empty otherwise the JSON.parse() will fail. In this case, you would want to initialize lcSettings to an empty object (lcSettings = {}) so the above will work.

Upvotes: 1

Related Questions