0

I'm taking a course on udemy and i'm really confused on how notes = JSON.parse(notesString) is an array when it's suppose to be an object (right?) since JSON.parse makes it an object.

var addNote = (title, body) => {
  var notes = []; // Create empty array
  var note = { // Fetch user input
    title,
    body
  };
  try {
    var notesString = fs.readFileSync("notes-data.json"); //  Get current notes
    notes = JSON.parse(notesString); // convert current notes into object
    console.log("try:", notes.constructor)
  }catch(e){

  }
  console.log(notes)
  notes.push(note);
  fs.writeFileSync("notes-data.json", JSON.stringify(notes));
};
4
  • From this code it looks like it's an array. You commented it's an array yourself: var notes = []; // Create empty array Commented Jan 24, 2018 at 3:45
  • 4
    "since JSON.parse makes it an object" --- it does not. JSON.parse returns the value of the same type it was initially. Commented Jan 24, 2018 at 3:46
  • 2
    although technically an array is an object in javascript. Commented Jan 24, 2018 at 3:49
  • JSON.parse do just parsing json string into JSON. it can be an array of objects or simple object. Commented Jan 24, 2018 at 4:51

3 Answers 3

2

JSON.parse() is required over there because the output of a fs operation is a string which we need to convert into an object in order to access it properly. The data inside it is a JSON Array as a result we are able read it. Add try catch around the JSON.parse because if the data is not of JSON type then it will cause an error.

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

2 Comments

This is the proper answer. The key note to remember is that fs operation you're doing returns a //string//, not an object (or array for that matter).
Thank you, it's making sense now.
0

If JSON in file notes-data.json contains JSON-array, i.e. some content like

[{"one":1}, {"two":2}]

You will get array from JSON.parse method.

Comments

0

If JSON in file notes-data.json contains JSON-array, i.e. some content like

var data = "[{"one":1}, {"two":2}]";
var result = JSON.parse(data);
console.log(result)

1 Comment

Please add somes explanations editing your answer, avoid code only answer

Your Answer

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