user3273370
user3273370

Reputation: 25

Write and Delete elements from JSON file in Node

I'm currently reading in a JSON object file, and I'm trying to modify the elements and write back to it. I know this can easily be done with a MongoDB, but I need to do it with JSON files. My current structure looks like this:

{
  "lastupdated": "Thu Nov 20 2014 10:57:08 GMT-0500 (EST)",
  "restaurants" : {
    "McDonalds": {
      "Americas": [
        "Atlanta",
        "Cambridge",
        "Dayton"
      ],
      "Asia": [
        "Seoul",
        "Shanghai",
        "Singapore",
        "Tokyo"
      ],
      "Europe": [
        "Milan",
        "Madrid",
        "Amsterdamn"
      ]
  },
  "BurgerKing" : {
    "Americas": [
      "Atlanta",
      "Boston",
      "Charlottesville"
    ],
    "Asia" : [
        "Hong Kong",
        "Singapore",
        "Tokyo"
      ],
    "Europe" : [
        "Rome",
        "Madrid",
        "Dublin"
      ]
    }

  }
}

I want to be able to do something like json.add(object.restaurants.McDonalds.Americas.("Washington D.C.") and this will update tte file to look like:

{
  "lastupdated": "Thu Nov 20 2014 10:57:08 GMT-0500 (EST)",
  "restaurants" : {
    "McDonalds": {
      "Americas": [
        "Atlanta",
        "Cambridge",
        "Dayton",
        "Washington D.C."
      ],

I'm currently using FS to read it in and store it as a json object

Upvotes: 1

Views: 3829

Answers (2)

Himmet Avsar
Himmet Avsar

Reputation: 1531

You can require your json file first:

var myJsonObject = require("./myfile");

Now you can make changes:

myJsonObject.restaurants.push(...);

Now save your file back:

fs.writeFile("./myfile.json", JSON.stringify(myJsonObject, null, 4), function(err){
    //handle err, success
});

Upvotes: 2

Jay
Jay

Reputation: 19897

If you are already reading in the JSON file with fs.readFile and store the JSON string in a variable, you need to parse the JSON string, modify the parsed object, and then convert it back into a JSON string and write back with fs.writeFile

I haven't tested this, but roughly:

var fs = require('fs');
fs.readFile('pathToJSONData.json', function(err, data) {
  var obj = JSON.parse(data);
  obj.restaurants.McDonalds.Americas.push('Washington D.C.');
  var newJSON = JSON.stringify(obj);
  fs.writeFile('pathToJSONData.json', newJSON, function(err) {
    console.log('done');
  });
});

Upvotes: 2

Related Questions