jquery的ajax,取回的json串,怎么把null过滤成空串
发布网友
发布时间:2022-05-17 13:33
我来回答
共3个回答
懂视网
时间:2022-05-17 17:54
Requirement:
一个json object,并且可能包含一些空值或者空字符串,在页面显示的时候希望遇到空值显示“N/A”,但是有一部分值是允许空值的。因此希望通过筛选将空值设为“N/A”.例如希望学生的“age”和“score”如果为空显示“N/A”,而“sex”或者“comment”为空则不做处理。
代码如下:
var student = {
"name" : "Guo",
"sex" : "",
"age" : "",
"num ": 01,
"scores" : [
{
"subject" : "English",
"score" : 50,
"comment" : ""
},
{
"subject" : "Computer",
"score" : "",
"comment" : "absent"
}
]
};
var exclude = ["sex", "comment"];
// method 1 to validate obj
validateObj1 = function(obj, excluded){
var value;
for(var key in obj){
value = obj[key];
if($.isArray(value)){
obj = validateArray1(obj, key, excluded);
}else if(($.inArray(key, excluded) == -1) && ($.isBlank(value))){
obj[key] = "N/A";
}
}
return obj;
}
validateArray1 = function(obj, key, excluded){
var subValue;
for(var i = 0, length = obj[key].length; i < length; i++){
for(var subKey in obj[key][i]){
subValue = obj[key][i][subKey];
if(($.inArray(subKey, excluded) == -1) && ($.isBlank(subValue))){
obj[key][i][subKey] = "N/A";
}
}
}
return obj;
}
// method 2 to validate obj
validateObj2 = function(obj, excluded){
$.each(obj ,function(key, value){
if($.isArray(value)){
obj = validateArray2(obj, key, excluded);
}else if(isInvalid(key, value, excluded)){
obj[key] = "N/A";
}
});
return obj;
}
validateArray2 = function(obj, key, excluded){
for(var i = 0, length = obj[key].length; i < length; i++){
$.each(obj[key][i] ,function(subKey, subValue){
if(isInvalid(subKey, subValue, excluded)){
obj[key][i][subKey] = "N/A";
}
});
}
return obj;
}
isInvalid = function(key, value, excluded){
return (($.inArray(key, excluded) == -1) && ($.isBlank(value))) ? true : false;
}
$.isBlank = function(obj){
return(!obj || $.trim(obj) === "");
};
Method 1 结果
Method 2 结果
热心网友
时间:2022-05-17 15:02
可以重新赋值。
如果json={"SSGM":null}
JSONObject jsonObj = new JSONObject(json);
String SSGM = jsonObj.get("SSGM");//获取JSON中SSGM的值便于判断
if(null == SSGM) {
jsonObj .put("SSGM","")//如果为null那么将SSGM的值赋值为""
}
不知道你的需求是什么,如果可以的话在写json的时候就做判断,或者从json拿数据的时候做判断是最方便的
热心网友
时间:2022-05-17 16:20
参数==null?"":参数