本篇文章将介绍关于使用node.js读取json文件内容,使用的是jsonfile模块的readfile和readfilesync函数。
要求:要在系统上安装node.js和npm。
对于本篇文章,我们使用的是jsonfile npm模块。因此,首先需要在系统上安装jsonfile模块
$ npm install jsonfile --save
现在,正在创建一个虚拟的json文件employee.json。也可以使用自己的json文件。
文件名:employee.json
[ { "emp_id" : "101", "emp_name" : "mike", "emp_addr" : "123 california, usa", "designation" : "editor" }, { "emp_id" : "102", "emp_name" : "jacob", "emp_addr" : "456 log angelis, usa", "designation" : "chief editor" }]
1、用nodejs读取json文件
在上面的步骤中,创建了一个json文件示例。现在创建readjsonfile.js并添加以下内容。需要使用json文件名更改employee.json。
文件名:readjsonfile.js
var jsonfile = require('jsonfile')var filename = 'employee.json'jsonfile.readfile(filename, function(err, jsondata) { if (err) throw err; for (var i = 0; i < jsondata.length; ++i) { console.log("emp id: "+jsondata[i].emp_id); console.log("emp name: "+jsondata[i].emp_name); console.log("emp address: "+jsondata[i].emp_addr); console.log("designation: "+jsondata[i].designation); console.log("----------------------------------"); }});
现在使用以下命令运行nodejs脚本。
$ node readjsonfile.js emp id: 101emp name: mikeemp address: 123 california, usadesignation: editor----------------------------------emp id: 102emp name: jacobemp address: 456 log angelis, usadesignation: chief editor----------------------------------
2、用nodejs读取json文件
或者,可以使用readfilesync函数读取json文件内容。创建一个包含以下内容的readjsonfilesync.js文件
文件名:readjsonfilesync.js
var jsonfile = require('jsonfile')var filename = 'employee.json'var jsondata = jsonfile.readfilesync(filename);for (var i = 0; i < jsondata.length; ++i) { console.log("emp id : "+jsondata[i].emp_id); console.log("emp name : "+jsondata[i].emp_name); console.log("emp address : "+jsondata[i].emp_addr); console.log("designation : "+jsondata[i].designation); console.log("----------------------------------");}
现在使用以下命令运行nodejs脚本。
$ node readjsonfilesync.js emp id: 101emp name: mikeemp address: 123 california, usadesignation: editor----------------------------------emp id: 102emp name: jacobemp address: 456 log angelis, usadesignation: chief editor----------------------------------
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注的node.js视频教程栏目!!!
以上就是如何使用node.js读取json文件的详细内容。