我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?
当前回答
您可以使用JSON.parse()(这是一个内置函数,可能会强制您使用try-catch语句包装它)。
或者使用一些JSON解析npm库,比如JSON -parse- Or
其他回答
您可以使用JSON.parse()(这是一个内置函数,可能会强制您使用try-catch语句包装它)。
或者使用一些JSON解析npm库,比如JSON -parse- Or
如果你想在你的JSON中添加一些注释,并允许尾随逗号,你可能想使用下面的实现:
var fs = require('fs');
var data = parseJsData('./message.json');
console.log('[INFO] data:', data);
function parseJsData(filename) {
var json = fs.readFileSync(filename, 'utf8')
.replace(/\s*\/\/.+/g, '')
.replace(/,(\s*\})/g, '}')
;
return JSON.parse(json);
}
注意,如果JSON中有"abc": "foo // bar"这样的东西,它可能无法正常工作。所以YMMV。
只是为了让这个问题尽可能复杂,并引入尽可能多的包……
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服务器可以处理其他请求。
利用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
我用的是fs-extra。我非常喜欢它,因为——尽管它支持回调——它也支持承诺。所以它只是让我以一种更可读的方式编写代码:
const fs = require('fs-extra');
fs.readJson("path/to/foo.json").then(obj => {
//Do dome stuff with obj
})
.catch(err => {
console.error(err);
});
它还提供了许多标准fs模块中没有的有用方法,除此之外,它还连接了来自本地fs模块的方法并对它们进行了承诺。
注意:你仍然可以使用原生Node.js方法。它们被承诺并复制到fs-extra。参见fs.read() & fs.write()的注释
所以基本上都是优势。我希望这对其他人有用。