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));
};
3 Answers 3
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.
2 Comments
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
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)
var notes = []; // Create empty arrayJSON.parsereturns the value of the same type it was initially.