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

JSON.parse(str);

如果JSON源文件相当大,可以考虑通过Node.js 8.0的原生异步/ await方法实现异步路由,如下所示

const fs = require('fs')

const fsReadFile = (fileName) => {
    fileName = `${__dirname}/${fileName}`
    return new Promise((resolve, reject) => {
        fs.readFile(fileName, 'utf8', (error, data) => {
            if (!error && data) {
                resolve(data)
            } else {
                reject(error);
            }
        });
    })
}

async function parseJSON(fileName) {
    try {
        return JSON.parse(await fsReadFile(fileName));
    } catch (err) {
        return { Error: `Something has gone wrong: ${err}` };
    }
}

parseJSON('veryBigFile.json')
    .then(res => console.log(res))
    .catch(err => console.log(err))

您可以使用JSON.parse()(这是一个内置函数,可能会强制您使用try-catch语句包装它)。

或者使用一些JSON解析npm库,比如JSON -parse- Or

使用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

利用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