我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?
当前回答
我用的是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()的注释
所以基本上都是优势。我希望这对其他人有用。
其他回答
解析JSON流?使用JSONStream。
var request = require('request')
, JSONStream = require('JSONStream')
request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
.pipe(JSONStream.parse('rows.*'))
.pipe(es.mapSync(function (data) {
return data
}))
https://github.com/dominictarr/JSONStream
只是为了让这个问题尽可能复杂,并引入尽可能多的包……
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.parse。
JSON对象的定义是ECMAScript 5规范的一部分。node.js基于谷歌Chrome V8引擎,符合ECMA标准。因此,node.js也有一个全局对象JSON[docs]。
注- JSON。Parse会占用当前线程,因为它是一个同步方法。因此,如果您计划解析大型JSON对象,请使用流式JSON解析器。
我用的是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()的注释
所以基本上都是优势。我希望这对其他人有用。
如果你想在你的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。