1

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

2 Answers 2

2

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');
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

it will work but it will have data read limitation if data inside the file is too large.
2

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.