我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?
当前回答
正如这里提到的其他答案,你可能想要一个本地json文件,你知道是安全的,就像一个配置文件:
var objectFromRequire = require('path/to/my/config.json');
或者使用全局JSON对象将字符串值解析为对象:
var stringContainingJson = '\"json that is obtained from somewhere\"';
var objectFromParse = JSON.parse(stringContainingJson);
请注意,当您需要一个文件时,该文件的内容会被评估,如果它不是json文件而是js文件,则会引入安全风险。
在这里,我发布了一个演示,你可以看到这两种方法,并在线使用它们(解析示例在app.js文件中-然后点击运行按钮,在终端中看到结果): http://staging1.codefresh.io/labs/api/env/json-parse-example
您可以修改代码并查看影响…
其他回答
您可以简单地使用JSON.parse。
JSON对象的定义是ECMAScript 5规范的一部分。node.js基于谷歌Chrome V8引擎,符合ECMA标准。因此,node.js也有一个全局对象JSON[docs]。
注- JSON。Parse会占用当前线程,因为它是一个同步方法。因此,如果您计划解析大型JSON对象,请使用流式JSON解析器。
利用Lodash的attempt函数返回一个错误对象,可以用isError函数处理。
// Returns an error object on failure
function parseJSON(jsonString) {
return _.attempt(JSON.parse.bind(null, jsonString));
}
// Example Usage
var goodJson = '{"id":123}';
var badJson = '{id:123}';
var goodResult = parseJSON(goodJson);
var badResult = parseJSON(badJson);
if (_.isError(goodResult)) {
console.log('goodResult: handle error');
} else {
console.log('goodResult: continue processing');
}
// > goodResult: continue processing
if (_.isError(badResult)) {
console.log('badResult: handle error');
} else {
console.log('badResult: continue processing');
}
// > badResult: handle error
由于您不知道您的字符串实际上是有效的,因此我将首先将它放入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)
}
})
}
一定要确保使用JSON。如果你的json中有一些损坏的数据,那么使用这段代码而不是简单的json,解析try catch块作为节点总是抛出一个意外错误。解析
try{
JSON.parse(data)
}
catch(e){
throw new Error("data is corrupted")
}
正如在上面的答案中提到的,我们可以使用JSON.parse()将字符串解析为JSON 但是在解析之前,请确保解析正确的数据,否则可能会导致整个应用程序崩溃
这样使用是安全的
let parsedObj = {}
try {
parsedObj = JSON.parse(data);
} catch(e) {
console.log("Cannot parse because data is not is proper json format")
}