我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?
当前回答
使用JSON配置Node.js?阅读这篇文章,让你的配置技能超过9000…
Note: People claiming that data = require('./data.json'); is a security risk and downvoting people's answers with zealous zeal: You're exactly and completely wrong. Try placing non-JSON in that file... Node will give you an error, exactly like it would if you did the same thing with the much slower and harder to code manual file read and then subsequent JSON.parse(). Please stop spreading misinformation; you're hurting the world, not helping. Node was designed to allow this; it is not a security risk!
正确的应用程序有3层以上的配置:
服务器/容器配置 应用程序配置 (可选)租户/社区/组织配置 用户配置
大多数开发者都认为他们的服务器和应用配置是可以改变的。它不能。您可以在更高的层上逐层进行更改,但是您正在修改基本需求。有些东西需要存在!让你的配置像不可变一样,因为它的一些基本是不可变的,就像你的源代码一样。
如果没有看到你的很多东西在启动后不会改变,就会导致反模式,比如在配置加载中到处都是try/catch块,并且假装你可以在没有正确设置应用程序的情况下继续运行。你不能。如果可以,那就属于社区/用户配置层,而不是服务器/应用配置层。你只是做错了。当应用程序完成引导时,可选的东西应该分层在顶部。
不要用头撞墙:你的配置应该非常简单。
看看用一个简单的json配置文件和一个简单的app.js文件来设置一个像协议无关和数据源无关的服务框架这样复杂的东西是多么容易……
container-config.js……
{
"service": {
"type" : "http",
"name" : "login",
"port" : 8085
},
"data": {
"type" : "mysql",
"host" : "localhost",
"user" : "notRoot",
"pass" : "oober1337",
"name" : "connect"
}
}
index.js……(驱动一切的引擎)
var config = require('./container-config.json'); // Get our service configuration.
var data = require(config.data.type); // Load our data source plugin ('npm install mysql' for mysql).
var service = require(config.service.type); // Load our service plugin ('http' is built-in to node).
var processor = require('./app.js'); // Load our processor (the code you write).
var connection = data.createConnection({ host: config.data.host, user: config.data.user, password: config.data.pass, database: config.data.name });
var server = service.createServer(processor);
connection.connect();
server.listen(config.service.port, function() { console.log("%s service listening on port %s", config.service.type, config.service.port); });
app.js……(支持协议不可知和数据源不可知服务的代码)
module.exports = function(request, response){
response.end('Responding to: ' + request.url);
}
使用这种模式,你现在可以在你启动的应用程序上加载社区和用户配置的东西,开发运维已经准备好将你的工作推到一个容器中并扩展它。你是为多租户的。用户域是隔离的。现在,您可以分离使用的服务协议和数据库类型,只关注编写好的代码。
因为你在使用层,你可以在任何时候依赖于一个单一的真实来源(分层配置对象),并避免在每一步进行错误检查,担心“哦,糟糕,没有正确的配置,我怎么能让这个工作?!?”
其他回答
NodeJs是一个基于JavaScript的服务器,所以你可以用纯JavaScript的方式来做…
想象一下你在NodeJs中有这个Json…
var details = '{ "name": "Alireza Dezfoolian", "netWorth": "$0" }';
var obj = JSON.parse(details);
你可以通过上面的操作来获得json的解析版本…
您可以使用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,请确保完成了错误处理。
这里的每个人都讲过JSON。所以我想说点别的。有一个伟大的模块连接许多中间件,使应用程序的开发更容易和更好。中间件之一是bodyParser。它可以解析JSON, html表单等。还有一个仅用于JSON解析的特定中间件noop。
看看上面的链接,它可能对你很有帮助。
您可以简单地使用JSON.parse。
JSON对象的定义是ECMAScript 5规范的一部分。node.js基于谷歌Chrome V8引擎,符合ECMA标准。因此,node.js也有一个全局对象JSON[docs]。
注- JSON。Parse会占用当前线程,因为它是一个同步方法。因此,如果您计划解析大型JSON对象,请使用流式JSON解析器。
使用JSON配置Node.js?阅读这篇文章,让你的配置技能超过9000…
Note: People claiming that data = require('./data.json'); is a security risk and downvoting people's answers with zealous zeal: You're exactly and completely wrong. Try placing non-JSON in that file... Node will give you an error, exactly like it would if you did the same thing with the much slower and harder to code manual file read and then subsequent JSON.parse(). Please stop spreading misinformation; you're hurting the world, not helping. Node was designed to allow this; it is not a security risk!
正确的应用程序有3层以上的配置:
服务器/容器配置 应用程序配置 (可选)租户/社区/组织配置 用户配置
大多数开发者都认为他们的服务器和应用配置是可以改变的。它不能。您可以在更高的层上逐层进行更改,但是您正在修改基本需求。有些东西需要存在!让你的配置像不可变一样,因为它的一些基本是不可变的,就像你的源代码一样。
如果没有看到你的很多东西在启动后不会改变,就会导致反模式,比如在配置加载中到处都是try/catch块,并且假装你可以在没有正确设置应用程序的情况下继续运行。你不能。如果可以,那就属于社区/用户配置层,而不是服务器/应用配置层。你只是做错了。当应用程序完成引导时,可选的东西应该分层在顶部。
不要用头撞墙:你的配置应该非常简单。
看看用一个简单的json配置文件和一个简单的app.js文件来设置一个像协议无关和数据源无关的服务框架这样复杂的东西是多么容易……
container-config.js……
{
"service": {
"type" : "http",
"name" : "login",
"port" : 8085
},
"data": {
"type" : "mysql",
"host" : "localhost",
"user" : "notRoot",
"pass" : "oober1337",
"name" : "connect"
}
}
index.js……(驱动一切的引擎)
var config = require('./container-config.json'); // Get our service configuration.
var data = require(config.data.type); // Load our data source plugin ('npm install mysql' for mysql).
var service = require(config.service.type); // Load our service plugin ('http' is built-in to node).
var processor = require('./app.js'); // Load our processor (the code you write).
var connection = data.createConnection({ host: config.data.host, user: config.data.user, password: config.data.pass, database: config.data.name });
var server = service.createServer(processor);
connection.connect();
server.listen(config.service.port, function() { console.log("%s service listening on port %s", config.service.type, config.service.port); });
app.js……(支持协议不可知和数据源不可知服务的代码)
module.exports = function(request, response){
response.end('Responding to: ' + request.url);
}
使用这种模式,你现在可以在你启动的应用程序上加载社区和用户配置的东西,开发运维已经准备好将你的工作推到一个容器中并扩展它。你是为多租户的。用户域是隔离的。现在,您可以分离使用的服务协议和数据库类型,只关注编写好的代码。
因为你在使用层,你可以在任何时候依赖于一个单一的真实来源(分层配置对象),并避免在每一步进行错误检查,担心“哦,糟糕,没有正确的配置,我怎么能让这个工作?!?”