NodeJS - 解析JSON(只有字符串或数字)
I have got a little dilema what to do (What should I do). I've got in my app several places where I am using AJAX to transfer a JSON data. So for example receiving a data from the registration form:
我有一点困境做什么(我该怎么办)。我在我的应用程序中有几个地方,我使用AJAX传输JSON数据。例如,从注册表中接收数据:
try {
var data = JSON.parse(json);
}
catch(e) {
// ...
}
var fields = {
firstName: data.firstName || "",
lastName: data.lastName || "",
...
};
Then I need to do something with these fields. Let's say:
然后我需要对这些领域做点什么。让我们说:
if (fields.firstName) {
// OK save it to the DB
}
if(fields.lastName.xxx()) { // xxx() is a method that belongs to JS String Object
// Do something...
}
The problem is what if fields.firstName
or fields.lastName
is {}
/ []
? That may happen if somebody sent a modified JSON with a wrong data types, the whole app will then crash since the method xxx
is missing.
问题是如果fields.firstName或fields.lastName是{} / []?如果有人发送了带有错误数据类型的修改后的JSON,那么可能会发生这种情况,整个应用程序将因为缺少方法xxx而崩溃。
Do I have to check the type of every field whether it is really a string, a number, an array... or is there some another maybe nicer way how to do this?
我是否必须检查每个字段的类型是否真的是一个字符串,一个数字,一个数组......还是有另外一个可能更好的方法如何做到这一点?
3 个解决方案
#1
2
Unfortunately that's a problem you'll have to face anytime using a dynamic language like JavaScript.
不幸的是,使用动态语言(如JavaScript)时,您将不得不面对这个问题。
One possible solution is not using String methods, but creating a function that will check it's arguments first:
一种可能的解决方案是不使用String方法,而是创建一个首先检查它的参数的函数:
// original, with string methods
if (text instanceof String && text.trim().length === 0) { ... }
// alternative, define function first
var isEmptyString = function(text) {
if (!(text instanceof String)) throw new Error("Argument must be a String");
return text.trim().length === 0;
}
// use it in your code
if (isEmptyString(text)) { ... }
That can lead to cleaner code. Just be sure not to define those functions in a global scope, when you have to use them in a Browser. Within the node.js modules that should not be a problem.
这可以使代码更清晰。当您必须在浏览器中使用它们时,请确保不要在全局范围内定义这些函数。在node.js模块中应该不是问题。
更多相关文章
- 进行连续ajax调用的正确方法是什么?
- JavaScript数组操作函数方法详解
- 如何在单击按钮时将桌面应用程序导航到系统中设置的默认邮件提供
- Angular 2快速入门 - 我的应用程序组件未加载
- JavaScript中的数学对象中的方法
- JavaScript——数组(三)数组方法汇总
- 与jQuery ajax post方法相比,fetch方法没有按预期发布
- 在ExtJS中调用超类方法的更好方法
- contains和compareDocumentPosition 方法来确定是否HTML节点间的