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


当前回答

如果你想在你的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。

其他回答

利用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()的注释

所以基本上都是优势。我希望这对其他人有用。

您可以要求.json文件。

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

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

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

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

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

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

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

var fs = require('fs');

fs.readFile('ashish.json',{encoding:'utf8'},function(data,err) {

   if(err) 
      throw err;

   else {

   console.log(data.toString());

 }
})

包括node-fs库。

var fs = require("fs");
var file = JSON.parse(fs.readFileSync("./PATH/data.json", "utf8"));

有关'fs'库的更多信息,请参阅http://nodejs.org/api/fs.html的文档