Yallo, I am at ends as to why notes = JSON.parse(notesString) is converting my array to a string instead of passing my json strings into the array. I tested by checking the typeof before and after. I understand why push cannot be used because it's no longer an array. but I don't know the solution.
Code
// array to store notes in
var notes = [];
// note JSON object
var note = {
title: title,
body: body
};
try {
// read pre-existing content of notes-data.json file
var notesString = fs.readFileSync('notes-data.json');
// store pre-existing data as the notes array, passing as
// JSON
console.log("notesString: " + typeof notesString)
console.log("notes before parse: " + typeof notes)
notes = JSON.parse(notesString)
console.log("notes after parse:" + typeof notes)
} catch (e) {
}
// add note to notes array
notes.push(note)
// store content of notes array in notes-data.json as a string
fs.writeFileSync('notes-data.json', JSON.stringify(notes));
This is my JSON
"[{\"title\":\"herp\",\"body\":\"derp\"},{\"title\":\"herp\",\"body\":\"derp\"}]"
Output
notesString: object
notes before parse: object
notes after parse:string
C:\Visual Studio 2015\Projects\Note_App_NodeJS\Note_App_NodeJS\notes.js:32
notes.push(note)
^
TypeError: notes.push is not a function
Resolved sorry people I don't know what was going on but I should have validated my output/input first. I don't know why it was formatted in that manner and it's formatted in the correct json format since, when converting to stingify then parsing back. I am using Visual Studio with the Nodejs extension so perhaps that had something to do with it.
notes-data.json?SyntaxError: Unexpected end of JSON input(although your try/catch would hide that), it shouldn't get as far as logging "notes after parse".