JSON.parse转换为字符串,而不是传递给数组 [英] JSON.parse converting to a string instead of passing into array

查看:684
本文介绍了JSON.parse转换为字符串,而不是传递给数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Yallo,我想知道为什么notes = JSON.parse(notesString)将数组转换为字符串而不是将json字符串传递给数组.我通过前后检查typeof进行了测试.我知道为什么不能使用推,因为它不再是数组.但我不知道解决方案.

Yallo, I am at ends as to why notes = JSON.parse(notesString) is converting my array to a string instead of passing my json strings into the array. I tested by checking the typeof before and after. I understand why push cannot be used because it's no longer an array. but I don't know the solution.

代码

// 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,所以也许与它有关.

Resolved sorry people I don't know what was going on but I should have validated my output/input first. I don't know why it was formatted in that manner and it's formatted in the correct json format since, when converting to stingify then parsing back. I am using Visual Studio with the Nodejs extension so perhaps that had something to do with it.

推荐答案

由于有引号,所以它是一个字符串.如果删除这些内容,则您的JSON无效.您必须根据JSON规则设置其格式.所有键都必须是字符串,并且值只能是基元,例如字符串,数字,布尔值,数组或其他JSON对象.

It is a string because of the outer quotes. If you remove those, your JSON is not valid. You must format it according to the JSON rules. All the keys must be strings, and values can be only primitives, like strings, numbers, booleans, arrays or other JSON objects.

将JSON格式设置为

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

在这里您可以看到一些示例: http://json.org/example.html

Here you can see some examples: http://json.org/example.html

这篇关于JSON.parse转换为字符串,而不是传递给数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆