你好,我不明白为什么 notes = JSON.parse(notesString)
把我的数组转换成字符串而不是将我的json字符串传入数组。我通过检查typeof
来测试它的前后变化。我知道为什么不能使用push,因为它不再是一个数组,但我不知道解决方法。
代码
// 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
已解决 抱歉,大家。我不知道发生了什么事情,但我应该先验证我的输出/输入。我不知道为什么它以那种方式格式化,但当转换为 stringify 然后再解析时,它的格式化是正确的 JSON 格式。我使用带有 Nodejs 扩展的 Visual Studio,所以可能与此有关。
notes-data.json
是什么? - nicovank