我应该如何使用Node.js解析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
其他回答
JSON。解析将不能确保你正在解析的json字符串的安全性。您应该查看类似于json-safe-parse或类似的库。
来自json-safe-parse npm页面:
JSON。parse非常棒,但是它在JavaScript上下文中有一个严重的缺陷:它允许重写继承的属性。如果解析JSON来自一个不受信任的源(例如:用户),并在其上调用您希望存在的函数,这就会成为一个问题。
您可以简单地使用JSON.parse。
JSON对象的定义是ECMAScript 5规范的一部分。node.js基于谷歌Chrome V8引擎,符合ECMA标准。因此,node.js也有一个全局对象JSON[docs]。
注- JSON。Parse会占用当前线程,因为它是一个同步方法。因此,如果您计划解析大型JSON对象,请使用流式JSON解析器。
正如在上面的答案中提到的,我们可以使用JSON.parse()将字符串解析为JSON 但是在解析之前,请确保解析正确的数据,否则可能会导致整个应用程序崩溃
这样使用是安全的
let parsedObj = {}
try {
parsedObj = JSON.parse(data);
} catch(e) {
console.log("Cannot parse because data is not is proper json format")
}
正如这里提到的其他答案,你可能想要一个本地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()。
您应该能够在任何ECMAScript 5兼容的JavaScript实现上使用JSON对象。V8, Node.js就是其中之一。
注意:如果你使用JSON文件来存储敏感信息(例如密码),这是错误的做法。看看Heroku是怎么做的:https://devcenter.heroku.com/articles/config-vars#setting-up-config-vars-for-a-deployed-application。了解您的平台是如何做到这一点的,并使用流程。Env从代码中检索配置变量。
解析包含JSON数据的字符串
var str = '{ "name": "John Doe", "age": 42 }';
var obj = JSON.parse(str);
解析包含JSON数据的文件
你必须用fs模块做一些文件操作。
异步版本
var fs = require('fs');
fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
if (err) throw err; // we'll not consider error handling for now
var obj = JSON.parse(data);
});
同步版本
var fs = require('fs');
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));
你想用require?再想想!
有时你可以用require:
var obj = require('path/to/file.json');
但是,我不建议这样做,原因如下:
require is synchronous. If you have a very big JSON file, it will choke your event loop. You really need to use JSON.parse with fs.readFile. require will read the file only once. Subsequent calls to require for the same file will return a cached copy. Not a good idea if you want to read a .json file that is continuously updated. You could use a hack. But at this point, it's easier to simply use fs. If your file does not have a .json extension, require will not treat the contents of the file as JSON.
认真对待!使用JSON.parse。
load-json-file模块
如果您正在阅读大量的.json文件(如果您非常懒惰),那么每次都要编写样板代码就会变得很讨厌。您可以使用load-json-file模块保存一些字符。
const loadJsonFile = require('load-json-file');
异步版本
loadJsonFile('/path/to/file.json').then(json => {
// `json` contains the parsed object
});
同步版本
let obj = loadJsonFile.sync('/path/to/file.json');
从流解析JSON
如果JSON内容通过网络进行流式传输,则需要使用流式JSON解析器。否则,它将阻塞处理器并阻塞事件循环,直到JSON内容完全流化。
在NPM中有很多可用的包。选择最适合你的。
错误处理/安全
如果您不确定传递给JSON.parse()的内容是否是有效的JSON,请确保在try/catch块中包含对JSON.parse()的调用。用户提供的JSON字符串可能导致应用程序崩溃,甚至可能导致安全漏洞。如果解析外部提供的JSON,请确保完成了错误处理。