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