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


当前回答

我的解决方案:

var fs = require('fs');
var file = __dirname + '/config.json';

fs.readFile(file, 'utf8', function (err, data) {
    if (err) {
        console.log('Error: ' + err);
        return;
    }

    data = JSON.parse(data);

    console.dir(data);
});

其他回答

一定要确保使用JSON。如果你的json中有一些损坏的数据,那么使用这段代码而不是简单的json,解析try catch块作为节点总是抛出一个意外错误。解析

try{
     JSON.parse(data)
}
catch(e){
   throw new Error("data is corrupted")
  }

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

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

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

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

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

如果你需要用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。解析将不能确保你正在解析的json字符串的安全性。您应该查看类似于json-safe-parse或类似的库。

来自json-safe-parse npm页面:

JSON。parse非常棒,但是它在JavaScript上下文中有一个严重的缺陷:它允许重写继承的属性。如果解析JSON来自一个不受信任的源(例如:用户),并在其上调用您希望存在的函数,这就会成为一个问题。