简体   繁体   中英

how to update json value in fs which is read from fs in javascript?

Requirement: read from json file, update value and write to json file

I have a json file test.json which contains below data

test.json

{
    "login": "readfromjson",
    "pwd": "pwd",
    "taskName": "task",
   
    "selectors": [
        {
            "Edit": "Edit",
            "Complete": "Complete",
            "Review": "Review"
        }
    ]
}

function.js //contains function to read, update json value from fs

function writeToJsonKey(fileName, keyName, value){
    let fullpath = PATH.resolve(GETPATH, fileName);
    let rawdata = FS.readFileSync(fullpath,'utf8');
    console.log(rawdata) //returns data as per json and is of string type
    
    let data = JSON.parse(rawdata); 
    console.log(rawdata) //returns [object Object]
    
    var i;
    keyName = keyName.split('.');
    for (i = 0; i < keyName.length; i++)
    {           
        data = data[keyName[i]];            
    }   
    data[keyName[i]] = value;

    console.log(keyName[i]) //returns required key where update to be done
    console.log(data[keyName[i]]) //returns undefined??
    
    FS.writeFileSync(fullpath, JSON.stringify(data, null, 2), function (err) { 
        if (err) throw err;
        console.log('Saved!');
      });
}

function call

writeToJsonKey('data.json', 'selectors.0.Edit', 'updated value') 

Result: As shown in console.log, whole data of json gets replaced with 'Edit'.

Note: If I read json data like below, it works but has issue when read from fs.

var obj = {
        "login": "readfromjson",
        "pwd": "pwd",
        "taskName": "task",
       
        "selectors": [
            {
                "Edit": "Edit",
                "Complete": "Complete",
                "Review": "Review"
            }
        ]
    }

You are replacing data in each iteration with data[keyName[i]] which will result in Edit (as you have described).

I recommend using a little helper library like lodash , as this allows setting values at a specific path pretty easily:

const lodash = require('lodash');

function writeToJsonKey(fileName, keyName, value){
    let fullpath = PATH.resolve(GETPATH, fileName);
    let rawdata = FS.readFileSync(fullpath,'utf8');
    console.log(rawdata) //returns data as per json and is of string type
    
    const data = JSON.parse(rawdata); 
    lodash.set(data, keyName, value );
  
    
    FS.writeFileSync(fullpath, JSON.stringify(data, null, 2), function (err) { 
        if (err) throw err;
        console.log('Saved!');
      });
}

You can then call this function with:

writeToJsonKey('/path/to/file',  'selectors[0].Edit', 'updated value')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM