nodejs怎么读写json文件?方法介绍


本文摘自PHP中文网,作者青灯夜游,侵删。

nodejs怎么读写json文件?下面本篇文章给大家介绍一下nodejs读写json文件的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

相关推荐:《nodejs 教程》

读json文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

'use strict';

 

const fs = require('fs');

 

let rawdata = fs.readFileSync('student.json');

let student = JSON.parse(rawdata);

console.log(student);

 

写json文件:

'use strict';

 

const fs = require('fs');

 

let student = {

    name: 'Mike',

    age: 23,

    gender: 'Male',

    department: 'English',

    car: 'Honda'

};

  

let data = JSON.stringify(student);

fs.writeFileSync('student-2.json', data);

虽然这是我们想要写入的数据,但数据是一行字符串的形式,这对我们来说很难读取。
如果您希望序列化的JSON是人类可读的,那么更改JSON。Stringify函数:
let data = JSON.stringify(student, null, 2);

json 转为 csv

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// require json-2-csv module

const converter = require('json-2-csv');

const fs = require('fs');

 

// read JSON from a file

const todos = JSON.parse(fs.readFileSync('todos.json'));

 

// convert JSON array to CSV string

(async () => {

    try {

        const csv = await converter.json2csvAsync(todos);

 

        // print CSV string

        console.log(csv);

 

        // write CSV to a file

        fs.writeFileSync('todos.csv', csv);

 

    } catch (err) {

        console.log(err);

    }

})();

csv转为json

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

csv第一行为key,例如:  id,name,email,country,age

// require csvtojson module

const CSVToJSON = require('csvtojson');

 

// convert users.csv file to JSON array

(async () => {

    try {

        const users = await CSVToJSON().fromFile('users.csv');

 

        // log the JSON array

        console.log(users);

 

    } catch (err) {

        console.log(err);

    }

})();

更多编程相关知识,请访问:编程入门!!

以上就是nodejs怎么读写json文件?方法介绍的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

html格式化json的实例代码

使用源码如何编译安装nodejs

json数据格式有哪些

浅谈nodejs获取参数的几种方法

使用nodejs+robotjs控制鼠标键盘

nodejs怎么运行js文件

javascript json字符串如何转换成对象

深入浅析nodejs中的“洋葱模型”

浅谈nodejs文件模块中的fs.mkdir和fs.rmdir

nodejs怎么结束进程

更多相关阅读请进入《nodejs》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...