Yallo,我不知道为什么
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
已解决 抱歉,我不知道发生了什么,但我应该首先验证我的输出/输入。我不知道为什么它以这种方式格式化,并且它以正确的 json 格式格式化,因为当转换为 stingify 然后解析回来时。我正在使用带有 Nodejs 扩展的 Visual Studio,所以也许这与它有关。
由于外部引号,它是一个字符串。如果删除这些内容,您的 JSON 将无效。您必须根据 JSON 规则对其进行格式化。所有键必须是字符串,值只能是基元,如字符串、数字、布尔值、数组或其他 JSON 对象。
将 JSON 格式化为
[
{
"title": "herp",
"body":"derp"
},
{
"title":"herp",
"body":"derp"
}
]
在这里您可以看到一些示例:http://json.org/example.html
抱歉,我应该在它包含的那一刻更具体
"[{\"title\":\"herp\",\"body\":\"derp\"},{\"title\":\"herp\",\"body\":\"derp\"}]"
那是字符串的JSON表达式,这就是为什么你解析它时会得到一个字符串。
该字符串恰好包含一组嵌套的 JSON,这就是您要查找的数组。
从字符串中提取该数组并将其放入文件中。
[{"title":"herp","body":"derp"},{"title":"herp","body":"derp"}]
我知道这个问题很旧,但我遇到了同样的问题
这里有一个现成的函数可以解决这个问题,以防有人LSE。
const toJson = data => {
data = JSON.parse(data);
if (typeof (data) === 'string')
return toJson(data)
return data;
}