Yallo,我在結束爲什麼notes = JSON.parse(notesString)
正在將我的數組轉換爲字符串,而不是將我的json字符串傳遞到數組中。我通過前後檢查typeof
進行測試。我明白爲什麼push不能使用,因爲它不再是一個數組。但我不知道解決方案。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文件我正在存儲字符串化的json到 – gxminbdd