1

I have a JSON file that looks like this

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

how do I append this file in node.js? When I try fs.appendFile the JSON file ends up looking like this

{
    "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!

1
  • So you want to add the "nickname" property to the file? Commented Jul 15, 2015 at 20:28

1 Answer 1

1

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.

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.

Sign up to request clarification or add additional context in comments.

1 Comment

can you do this with variables? for example if nickname was instead a key, and "shmee" was a value could i do data[key] = value; and then the rest

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.