Yallo、私はなぜnotes = JSON.parse(notesString)
が配列に私のjson文字列を渡すのではなく、文字列に変換しているのかを知りました。私は前と後にtypeof
をチェックしてテストしました。なぜプッシュはもはや配列ではないので使用できない理由を理解しています。私は解決策を知らない。JSON.parseを配列に渡す代わりに文字列に変換する
コード
// 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));
これは私のJSON私は何が起こっていたか分からないが、私は持っている必要があり 申し訳ありません人々を解決
"[{\"title\":\"herp\",\"body\":\"derp\"},{\"title\":\"herp\",\"body\":\"derp\"}]"
出力
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
です私の出力/入力を最初に検証した。私はそれがなぜそのようにフォーマットされたのか分かりませんし、正しいjsonフォーマットで書かれています。なぜなら、stingifyに変換してから解析するからです。私はVisual StudioとNodejsエクステンションを使用していますので、おそらくそれと関係があります。
'notes-data.json'とは何ですか? – nicovank
これをテストしたところ、JSONファイルには配列ではなく文字列が含まれているという唯一の説明があります。あなたの[mcve]にはこの質問の理解に不可欠なJSONデータが欠けています。 – Quentin
空の.jsonファイル – gxminbdd