Darkrum
Darkrum

Reputation: 1373

Add data to existing json object

So what i'm trying to achieve is creating a json flat file to store user info where i'm stuck is that i don't know how to add new nested objects that are empty and then save the json file and reload it.

what i have in my *json* file is this.

{
    "users" : {
        "test" : {

        },
        "test1" : {

        }
    }
}

I'm trying to add as many new objects as i want to it. So for example.

{
    "users" : {
        "test" : {

        },
        "test1" : {

        },
        "test2" : {

        },
        "test3" : {

        }
    }
}

My server side Javascript

    json.users.push = username;
    fs.writeFile("./storage.json", JSON.stringify(json, null, 4) , 'utf-8');
    delete require.cache[require.resolve('./storage.json')];
    json = require("./storage.json");

With this code it does not write the file so when the require is done i end up with the same file and my json object ends up like this when i console.log it

{                                                                                                                                                    
    "users": {                                                                                                                                       
        "test": {},                                                                                                                                  
        "test1": {},                                                                                                                                 
        "push": "test2"                                                                                                                                
    }                                                                                                                                                
}

Please do not recommend some external module to solve something has simple as this. Also if any one can point me to a in depth json documentation that gets straight to the point with what i'm try to do it would be appreciated

Upvotes: 3

Views: 30783

Answers (1)

Mulan
Mulan

Reputation: 135197

Use [] to access a dynamic key on the object

json.users[username] = {a: 1, b: 2}

Be careful naming your variable like that tho because json the way you're using it is not JSON. JSON is a string, not an object with keys.

See the below demo for distinction

var json = '{"users":{"test1":{},"test2":{}}}';
var obj  = JSON.parse(json);
var newuser = 'test3';
obj.users[newuser] = {};
console.log(JSON.stringify(obj));
//=> {"users":{"test1":{},"test2":{},"test3":{}}}

Upvotes: 3

Related Questions