2016-12-17 68 views
2

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擴展,所以也許這與它有關。

+2

什麼是'notes-data.json'? – nicovank

+0

經過測試,我能想出的唯一解釋是JSON文件包含一個字符串而不是一個數組。你的[mcve]缺少JSON數據,這對理解這個問題是很重要的。 – Quentin

+0

一個空的.json文件我正在存儲字符串化的json到 – gxminbdd

回答

3

這是一個字符串,因爲外部引號。如果你刪除這些,你的JSON無效。您必須根據JSON規則對其進行格式化。所有的鍵必須是字符串,並且值可以只是基元,如字符串,數字,布爾值,數組或其他JSON對象。

格式的JSON像

[ 
    { 
     "title": "herp", 
     "body":"derp" 
    }, 
    { 
     "title":"herp"‌​‌​, 
     "body":"derp"‌ 
    ​} 
]‌​ 

在這裏你可以看到一些例子:http://json.org/example.html

+0

「你的JSON無效」 - 這是一個完全有效的字符串。 – Quentin

+0

如果他刪除外部引號,則不需要。他不想要一個字符串。 – germanfr

1

sorry I should have been more specific at the momment it contains

"[{\"title\":\"herp\",\"body\":\"derp\"},{\"title\":\"herp\"‌​,\"body\":\"derp\"}]‌​" 

這是一個字符串的JSON表達,這就是爲什麼,當你分析它得到一個字符串。

該字符串恰好包含一組嵌套的JSON,它是您正在查找的數組。

從字符串中提取數組並將其放入文件中。

[{"title":"herp","body":"derp"},{"title":"herp"‌​,"body":"derp"}]‌​