如何更新json文件中的值并通过node.js保存

3htmauhk  于 2022-12-27  发布在  Node.js
关注(0)|答案(8)|浏览(164)

如何更新json文件中的值并通过node.js保存?我有文件内容:

var file_content = fs.readFileSync(filename);
var content = JSON.parse(file_content);
var val1 = content.val1;

现在我想更改val1的值并将其保存到文件中。

utugiqy6

utugiqy61#

异步执行此操作非常简单。如果您担心阻塞线程(可能),则此操作特别有用。否则,我建议使用里昂的答案

const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);
    
file.key = "new value";
    
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

需要注意的是,json只写在文件的一行上,而不是美化。例如:

{
  "key": "value"
}

将会是...

{"key": "value"}

要避免这种情况,只需将这两个额外的参数添加到JSON.stringify

JSON.stringify(file, null, 2)

null-表示替换函数。(在这种情况下,我们不想改变过程)
2-表示要缩进的空格。

y53ybaqx

y53ybaqx2#

//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));
w8biq8rn

w8biq8rn3#

// read file and make object
let content = JSON.parse(fs.readFileSync('file.json', 'utf8'));
// edit or add property
content.expiry_date = 999999999999;
//write file
fs.writeFileSync('file.json', JSON.stringify(content));
r1wp621o

r1wp621o4#

在上一个答案的基础上添加写入操作的add file path目录

fs.writeFile(path.join(__dirname,jsonPath), JSON.stringify(newFileData), function (err) {})
rks48beu

rks48beu5#

我强烈建议不要使用同步(阻塞)函数,因为它们会占用其他并发操作,而应该使用异步fs。

const fs = require('fs').promises

const setValue = (fn, value) => 
  fs.readFile(fn)
    .then(body => JSON.parse(body))
    .then(json => {
      // manipulate your data here
      json.value = value
      return json
    })
    .then(json => JSON.stringify(json))
    .then(body => fs.writeFile(fn, body))
    .catch(error => console.warn(error))

请记住setValue返回一个待定的承诺,您需要使用.then function,或者在异步函数中使用await operator

// await operator
await setValue('temp.json', 1)           // save "value": 1
await setValue('temp.json', 2)           // then "value": 2
await setValue('temp.json', 3)           // then "value": 3

// then-sequence
setValue('temp.json', 1)                 // save "value": 1
  .then(() => setValue('temp.json', 2))  // then save "value": 2
  .then(() => setValue('temp.json', 3))  // then save "value": 3
nhaq1z21

nhaq1z216#

对于希望向json集合添加项的用户

function save(item, path = './collection.json'){
    if (!fs.existsSync(path)) {
        fs.writeFile(path, JSON.stringify([item]));
    } else {
        var data = fs.readFileSync(path, 'utf8');  
        var list = (data.length) ? JSON.parse(data): [];
        if (list instanceof Array) list.push(item)
        else list = [item]  
        fs.writeFileSync(path, JSON.stringify(list));
    }
}
fruv7luv

fruv7luv7#

任务完成后保存数据

fs.readFile("./sample.json", 'utf8', function readFileCallback(err, data) {
        if (err) {
          console.log(err);
        } else {
          fs.writeFile("./sample.json", JSON.stringify(result), 'utf8', err => {
            if (err) throw err;
            console.log('File has been saved!');
          });
        }
      });
jw5wzhpr

jw5wzhpr8#

基于承诺的解决方案[Javascript**(ES6)+ Node.js(V10或更高版本)**]

const fsPromises = require('fs').promises;
fsPromises.readFile('myFile.json', 'utf8') 
        .then(data => { 
                let json = JSON.parse(data);
                //// Here - update your json as per your requirement ////

                fsPromises.writeFile('myFile.json', JSON.stringify(json))
                        .then(  () => { console.log('Update Success'); })
                        .catch(err => { console.log("Update Failed: " + err);});
            })
        .catch(err => { console.log("Read Error: " +err);});

如果您的项目支持JavascriptES 8,那么您可以使用asyn/await代替原生promise。

相关问题