2016-12-17 66 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"}]‌​