读取json文件

##读取json文件

Parsing a string containing JSON data

var str = '{ "name": "John Doe", "age": 42 }';
var obj = JSON.parse(str);

Parsing a file containing JSON data

You’ll have to do some file operations with fs module:

var fs = require('fs');

Then you can read the data asynchronously/synchronously.

Asynchronous version

fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
if (err) throw err; // we'll not consider error handling for now
var obj = JSON.parse(data);
});

Synchronous version

var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));

WARNING

You can sometimes use require:

var obj = require('path/to/file.json');

But, this is not recommended for several reasons:

require will read the file only once. Subsequent calls to require for the same file will return a cached copy. Not a good idea if you want to read a .json file that is continuously updated.
If your file does not have a .json extension, require will not treat the contents of the file as JSON.
JSON is not a true subset of JavaScript. A user provided JSON string could crash your application. Seriously. Use JSON.parse with a try/catch block.
jsonfile module

If you are reading large number of .json files, (and if you are extremely lazy), it becomes annoying to write boilerplate code every time. You can save some characters by using the jsonfile module.

var jf = require('jsonfile');

// asynchronous version
jf.readFile('/path/to/file.json', function(err, obj) {
  // obj contains JSON data
});

// synchronous version
var obj = jf.readFileSync(file);