我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?


当前回答

利用Lodash的attempt函数返回一个错误对象,可以用isError函数处理。

// Returns an error object on failure
function parseJSON(jsonString) {
   return _.attempt(JSON.parse.bind(null, jsonString));
}


// Example Usage
var goodJson = '{"id":123}';
var badJson = '{id:123}';
var goodResult = parseJSON(goodJson);
var badResult = parseJSON(badJson);

if (_.isError(goodResult)) {
   console.log('goodResult: handle error');
} else {
   console.log('goodResult: continue processing');
}
// > goodResult: continue processing

if (_.isError(badResult)) {
   console.log('badResult: handle error');
} else {
   console.log('badResult: continue processing');
}
// > badResult: handle error

其他回答

JSON的另一个例子。解析:

var fs = require('fs');
var file = __dirname + '/config.json';

fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    console.log('Error: ' + err);
    return;
  }

  data = JSON.parse(data);

  console.dir(data);
});

我想提一下全局JSON对象的替代方案。 JSON。解析和JSON。stringify都是同步的,所以如果你想处理大对象,你可能想查看一些异步JSON模块。

看看:https://github.com/joyent/node/wiki/Modules#wiki-parsers-json

只是为了让这个问题尽可能复杂,并引入尽可能多的包……

const fs = require('fs');
const bluebird = require('bluebird');
const _ = require('lodash');
const readTextFile = _.partial(bluebird.promisify(fs.readFile), _, {encoding:'utf8',flag:'r'});
const readJsonFile = filename => readTextFile(filename).then(JSON.parse);

这让你做:

var dataPromise = readJsonFile("foo.json");
dataPromise.then(console.log);

或者如果你使用async/await:

let data = await readJsonFile("foo.json");

与仅使用readFileSync相比的优点是,在从磁盘读取文件时,Node服务器可以处理其他请求。

您可以要求.json文件。

var parsedJSON = require('./file-name');

例如,如果你有一个配置。Json文件在相同的目录作为你的源代码文件,你会使用:

var config = require('./config.json');

或(文件扩展名可以省略):

var config = require('./config');

注意require是同步的,只读取文件一次,后续调用从缓存返回结果

还要注意,您应该只对完全控制下的本地文件使用此选项,因为它可能会执行文件中的任何代码。

使用JSON对象:

JSON.parse(str);