我应该如何使用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

其他回答

NodeJs是一个基于JavaScript的服务器,所以你可以用纯JavaScript的方式来做…

想象一下你在NodeJs中有这个Json…

var details = '{ "name": "Alireza Dezfoolian", "netWorth": "$0" }';
var obj = JSON.parse(details);

你可以通过上面的操作来获得json的解析版本…

使用JSON.parse (str);。点击这里阅读更多信息。

下面是一些例子:

var jsonStr = '{"result":true, "count":42}';

obj = JSON.parse(jsonStr);

console.log(obj.count);    // expected output: 42
console.log(obj.result);   // expected output: true

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

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);