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


当前回答

如果你需要用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,解析try catch块作为节点总是抛出一个意外错误。解析

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

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

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

JSON.parse("your string");

这是所有。

不需要其他模块。 只使用 var parsedObj = JSON.parse(yourObj); 我不认为这有任何安全问题

JSON。解析将不能确保你正在解析的json字符串的安全性。您应该查看类似于json-safe-parse或类似的库。

来自json-safe-parse npm页面:

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