Home > other >  how to add element to json file? (js)
how to add element to json file? (js)

Time:10-20

there is a file with a value

{"IpAddress":"1227.0.0.1","Login":"testuser","Password":"12345678","test":{"test1":"444","test2":"test2"}}

I want to add a new element and get this file (add test2:{test1: "444"})

{"IpAddress":"1227.0.0.1","Login":"testuser","Password":"12345678","test":{"test1":"444","test2":"test2"}, test2:{test1: "444"}}

I'm trying to do this but it doesn't work :(

   fs.access(PathConfigFile, function(error){
    let jsonFile;
    let configData;

        if (error){
            console.log("file not exist $PathConfigFile");
            let MySQL = {
                IpAddress: "127.0.0.1",
                Login: "testuser",
                Password: "12345678",
                test: {
                    test1: "tes1",
                    test2: "test2"
                }
               };            
            jsonFile =JSON.stringify(MySQL);
            fs.writeFileSync(PathConfigFile, jsonFile);
        } else {
            jsonFile = fs.readFileSync(PathConfigFile, "utf8"); 
            configData = JSON.parse(jsonFile);                  
            configData.IpAddress = "1227.0.0.1";
            configData.Login = "testuser";
            configData.Password = "12345678";
            configData.test.test1 = "444";   //<-this OK
            configData.test2.test1 = "444";     //<-this NOT OK


            jsonFile =JSON.stringify(configData);

            fs.writeFileSync(PathConfigFile, jsonFile);

        }
};

CodePudding user response:

const obj = JSON.parse(readFile);
obj.test2 = {test1: "444"};
const stringified = JSON.stringify(obj)
//now you can write this variable stringified to ur json file
  • Related