如何更新json文件中的值并通过node.js保存 [英] How to update a value in a json file and save it through node.js

查看:203
本文介绍了如何更新json文件中的值并通过node.js保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I update a value in a json file and save it through node.js? I have the file content:

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

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

Now I want to change the value of val1 and save it to the file.

推荐答案

异步进行此操作非常容易.如果您担心(可能)阻塞线程,则该功能特别有用.

Doing this asynchronously is quite easy. It's particularly useful if you're concerned for blocking the thread (likely).

var fs = require('fs');
var fileName = './file.json';
var file = require(fileName);

file.key = "new value";

fs.writeFile(fileName, JSON.stringify(file), function (err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

需要注意的是,json是在一行中写入到文件中的,没有经过修饰.例如:

The caveat is that json is written to the file on one line and not prettified. ex:

{
  "key": "value"
}

将是...

{"key": "value"}

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

To avoid this, simply add these two extra arguments to JSON.stringify

JSON.stringify(file, null, 2)

null-表示替换器功能. (在这种情况下,我们不想更改流程)

null - represents the replacer function. (in this case we don't want to alter the process)

2-表示要缩进的空格.

2 - represents the spaces to indent.

这篇关于如何更新json文件中的值并通过node.js保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆