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


当前回答

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

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

其他回答

只是为了让这个问题尽可能复杂,并引入尽可能多的包……

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服务器可以处理其他请求。

我用的是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.parse("your string");

这是所有。

解析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

如果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))