验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

怎么使用Node.js进行JSON数据的增删改查

阅读:1373 来源:乙速云 作者:代码code

怎么使用Node.js进行JSON数据的增删改查

  1. 增加JSON数据

Node.js提供了fs模块用于读取和写入文件。使用fs模块可以轻松地将JSON数据保存到文件中。

首先,我们需要创建一个JSON对象,并将其保存到文件中。在下面的代码片段中,我们创建了一个students.json文件,并将JSON对象写入该文件:

const fs = require('fs');

const students = {
  "Tom": {
    "age": 18,
    "gender": "male"
  },
  "Lily": {
    "age": 19,
    "gender": "female"
  }
};

fs.writeFile('students.json', JSON.stringify(students), (err) => {
  if (err) throw err;
  console.log('The JSON data has been saved!');
});

在上面的代码中,写入文件的方法是fs.writeFile(),它需要三个参数:文件名、数据和回调函数。 回调函数接受一个错误对象作为参数,如果写入成功,则返回null。

  1. 读取JSON数据

读取JSON数据也很简单。我们只需要使用fs.readFile()方法从文件中读取数据,并使用JSON.parse()方法将其转换为JSON对象。

const fs = require('fs');

fs.readFile('students.json', (err, data) => {
  if (err) throw err;
  const students = JSON.parse(data);
  console.log(students);
});

在上面的代码中,我们读取了students.json文件,并使用fs.readFile()方法将其转换为JSON对象。 回调函数接受一个错误对象和数据作为参数。 如果存在错误,则err参数将包含错误信息,否则将包含文件的内容。

  1. 修改JSON数据

要修改JSON数据,我们只需要使用JavaScript的对象属性访问符号(.)或方括号访问符号([])来更改对象中的属性。

const fs = require('fs');

fs.readFile('students.json', (err, data) => {
  if (err) throw err;
  const students = JSON.parse(data);
  
  // 修改Tom的年龄为20
  students.Tom.age = 20;
  
  fs.writeFile('students.json', JSON.stringify(students), (err) => {
    if (err) throw err;
    console.log('The JSON data has been updated!');
  });
});

在上面的代码中,我们读取了students.json文件,并将其转换为JSON对象。 然后,我们将Tom的年龄更改为20,并将更改后的数据写回到文件中。

  1. 删除JSON数据

要从JSON对象中删除属性,我们可以使用delete关键字。

const fs = require('fs');

fs.readFile('students.json', (err, data) => {
  if (err) throw err;
  const students = JSON.parse(data);
  
  // 删除Lily
  delete students.Lily;
  
  fs.writeFile('students.json', JSON.stringify(students), (err) => {
    if (err) throw err;
    console.log('The JSON data has been updated!');
  });
});

在上面的代码中,我们删除了students对象中的Lily属性,并将更改后的数据写回到文件中。

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>