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


当前回答

包括node-fs库。

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

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

其他回答

如果你需要用Node.js以一种安全的方式解析JSON(也就是说:用户可以输入数据,或者一个公共API),我建议使用secure- JSON -parse。

其用法类似于默认的JSON。解析,但它会保护你的代码:

原型中毒 和构造函数滥用:

const badJson = '{ "a": 5, "b": 6, "__proto__": { "x": 7 }, "constructor": {"prototype": {"bar": "baz"} } }'

const infected = JSON.parse(badJson)
console.log(infected.x) // print undefined

const x = Object.assign({}, infected)
console.log(x.x) // print 7

const sjson = require('secure-json-parse')
console.log(sjson.parse(badJson)) // it will throw by default, you can ignore malicious data also

您可以简单地使用JSON.parse。

JSON对象的定义是ECMAScript 5规范的一部分。node.js基于谷歌Chrome V8引擎,符合ECMA标准。因此,node.js也有一个全局对象JSON[docs]。

注- JSON。Parse会占用当前线程,因为它是一个同步方法。因此,如果您计划解析大型JSON对象,请使用流式JSON解析器。

JSON.parse("your string");

这是所有。

由于您不知道您的字符串实际上是有效的,因此我将首先将它放入try catch中。另外,由于try catch块不是按节点优化的,我将把整个事情放在另一个函数中:

function tryParseJson(str) {
    try {
        return JSON.parse(str);
    } catch (ex) {
        return null;
    }
}

“异步风格”的OR

function tryParseJson(str, callback) {
    process.nextTick(function () {
      try {
          callback(null, JSON.parse(str));
      } catch (ex) {
          callback(ex)
      }
    })
}

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

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