Node.js:从文件读取时,有任何库可以清除json(例如注释)吗? [英] Nodejs: any library to clean json (say comments) when reading from file?
问题描述
我正在使用require("fs")
读取Node.js中的json文件.
I'm reading json files in Node.js using require("fs")
.
类似:
var readJsonFromFile= function(fileLocation, callback){
fs.readFile(fileLocation, 'utf8', function (err, data) {
if (err) {
return callback(err);
}
data = JSON.parse(data);
callback(null,data);
});
}
但是,我注意到了JSON.parse
:
- 不允许评论
// bla
或/* blaa */
- 需要引号.
尽管我知道这在技术上是正确的,但我想知道是否存在任何小的库可以清理我经常注释的json文件以确保上述结果. (而且,这不是完全无关紧要的DIY,将//
视为有效值的一部分,等等.)
Although I realize this is technically correct, I'd like to know if any small library exists which cleans my often annotated json-files to guarentee the above. (And no, it's not completely trivial DIY, think //
as part of valid values, etc. )
谢谢
推荐答案
是的!为此,我使用Kyle Simpson的JSON.minify:
Yes! I use JSON.minify by Kyle Simpson for this very purpose:
https://github.com/getify/JSON.minify
这不是一个成熟的Node模块,但是它非常适合加载类似JSON的配置文件等.请注意,您仍然必须引用密钥,但它确实允许发表评论.
It isn't a full-blown Node module, but it works very well for loading JSON-like config files and such. Note that you still have to quote your keys, but it does allow for comments.
var config = JSON.parse(JSON.minify(fs.readFileSync(configFileName, 'utf8')));
这篇关于Node.js:从文件读取时,有任何库可以清除json(例如注释)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!