javascript - 将 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"}
解决方案
我认为你在这里摸索你的变量。据我了解-您想从文件中读取 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));
}
推荐阅读
- javascript - 使用按钮更改 div 宽度
- sql-server - 在没有 sas/access 许可的情况下使用 SAS 从 SQL Server 读取数据
- javascript - 从模板的输入动态地形成输入,到服务中的一个函数 - Angular
- sql-server - 将 XML 解析为 (XPath, Value) 对
- reactjs - 是否可以将导出的 sass 变量列表转换为 TypeScript 联合类型(NextJs/React)
- php - 相同字符串值中的两个 bindParam
- c# - Datetimeoffset 没有给出正确的格式
- r - 是否有更快的方法对数据框中的选定列进行逐行求和?
- amazon-web-services - 如何在 .Net Core API 中安全地存储 AWS 访问密钥和秘密密钥
- python - 将 django-music-publisher==21.5.1 集成到 django-oscar 3.1 应用程序中会引发“django.core.exceptions.AppRegistryNotReady:模型尚未加载”。