将JSON.parse转换为字符串而不是传递到数组中

3

你好,我不明白为什么 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

已解决 抱歉,大家。我不知道发生了什么事情,但我应该先验证我的输出/输入。我不知道为什么它以那种方式格式化,但当转换为 stringify 然后再解析时,它的格式化是正确的 JSON 格式。我使用带有 Nodejs 扩展的 Visual Studio,所以可能与此有关。


2
notes-data.json 是什么? - nicovank
一个空的 .json 文件,我正在将字符串化的 JSON 存储到其中。 - gxminbdd
你可以在fs.readFileSync之后发布“console.log(JSON.stringify(notesString))”的输出吗?我想我知道原因了。 - Akshay Kumar
如果您删除外部引号,它将抛出错误“意外的标记\”。 - sajan
@sajankumarvijayan 这是因为你的 JSON 是无效的。你必须删除所有的 \。键和值必须是字符串。 - germanfr
显示剩余7条评论
2个回答

4

由于外层引号,它是一个字符串。如果您删除这些引号,您的JSON将无效。您必须根据JSON规则对其进行格式化。所有键都必须是字符串,值只能是原始类型,如字符串、数字、布尔值、数组或其他JSON对象。

请按以下方式格式化您的JSON

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

这是一些示例:http://json.org/example.html


"您的JSON格式不正确" - 这是一个完全有效的字符串。 - Quentin
如果他去掉外面的引号,那么就不会是一个字符串了。 - germanfr

3

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"}]‌​

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接