首页 > 解决方案 > 将 JSON.parse() 返回类型转换为对象数组

问题描述

我定义了一个名为 note-data.json 的文件,其中包含 json 数据。在下面的代码中,声明了一个名为 notes 的数组类型的变量。我想要实现的是程序读取json文件将其保存在noteString变量中,然后使用noteString中的JSON.parse()创建一个对象数组并将其放入notes数组中。所以我可以将新对象添加到 json 文件中。但是当程序到达 note.push() 行时,它会抱怨,因为我认为笔记的类型已经变成了字符串,并且没有为字符串定义 push。我该如何解决这个问题?

请忽略这样一个事实,即如果未提供 json 文件,程序会崩溃。

我的代码:

const addNote = (title, body) => {
  let notes= [];
  const note = {

    title,
    body
  };

  const notesString = fs.readFileSync('node-data.json', 'utf8');
  notes = JSON.parse(notesString);

  notes.push(note);
  fs.writeFileSync('node-data.json', JSON.stringify(note));
}

文件 note-data.json:

{"title":"Greeting","body":"Hello"}

标签: javascriptnode.js

解决方案


我认为你在这里摸索你的变量。据我了解-您想从文件中读取 JSON 并将该 JSON 附加到数组中,对吗?以下代码将帮助您做到这一点

const addNote = (title, body) => {

  let notes= []; //Declare an array
  const note = JSON.parse(fs.readFileSync('node-data.json', 'utf8')); //read and parse file contents
  notes.push(note); //Append new JSON to your array

  //This line below appears to have no purpose ??
  fs.writeFileSync('node-data.json', JSON.stringify(note));
}

推荐阅读