[英]JSON.parse converting to a string instead of passing into array
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"}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.