我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?
当前回答
使用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
其他回答
JSON.parse("your string");
这是所有。
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.parse()(这是一个内置函数,可能会强制您使用try-catch语句包装它)。
或者使用一些JSON解析npm库,比如JSON -parse- Or
我想提一下全局JSON对象的替代方案。 JSON。解析和JSON。stringify都是同步的,所以如果你想处理大对象,你可能想查看一些异步JSON模块。
看看:https://github.com/joyent/node/wiki/Modules#wiki-parsers-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