简体   繁体   English

在节点中附加JSON文件

[英]Appending JSON file in node

I have a JSON file that looks like this 我有一个看起来像这样的JSON文件

{
    "name": "John Doe",
    "address": "9 School Rd"    
}

how do I append this file in node.js? 如何将此文件附加到node.js中? When I try fs.appendFile the JSON file ends up looking like this 当我尝试fs.appendFile时,JSON文件最终看起来像这样

{
    "name": "John Doe",
    "address": "9 School Rd"    
}, 
"nickname": "shmee"

however this is obviously not what I want it to look like. 但是,这显然不是我想要的样子。 Thanks for your help! 谢谢你的帮助!

A very simple way of doing this would be to parse in the object as JSON then save back the stringified version to the file. 一种非常简单的方法是将对象解析为JSON,然后将字符串化的版本保存回文件中。

var data = require('./my-data-file.json'); // Will automatically parse JSON
data.nickname = "shmee";
fs.writeFile('./my-data-file.json', JSON.stringify(data, null, 4), options, callback);

The options and callback are optional but I suggest writing a callback because that will let you know when the data has been saved. 选项和回调是可选的,但是我建议编写一个回调,因为这将使您知道何时保存数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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