如何递归地在JavaScript对象的键和值中修剪空白?
我遇到了一个问题,尝试“清理”用户提供的JSON字符串并将其发送到我的其他代码进行进一步处理。
假设我们有一个用户提供的JSON字符串,其中属性键和值均为“string”类型。但是,在这种情况下存在问题的是,键和值不够干净。例如:{ " key_with_leading_n_trailing_spaces ": " my_value_with_leading_spaces" }。
这可能会对您编写的精美JavaScript程序造成问题,因为当您的代码尝试从此JSON对象中获取值时,不仅键不匹配,而且值也无法匹配。我在Google上找到了一些提示,但没有一个方法可以完全解决这个问题。
给定具有许多键和值中的空格的JSON。
var badJson = {
" some-key ": " let it go ",
" mypuppy ": " donrio ",
" age ": " 12.3",
" children ": [
{
" color": " yellow",
"name ": " alice"
}, {
" color": " silver ",
"name ": " bruce"
}, {
" color": " brown ",
" name ": " francis"
}, {
" color": " red",
" name ": " york"
},
],
" house": [
{
" name": " mylovelyhouse ",
" address " : { "number" : 2343, "road " : " boardway", "city " : " Lexiton "}
}
]
};
所以这就是我想出来的(借助lodash.js的帮助):
//I made this function to "recursively" hunt down keys that may
//contain leading and trailing white spaces
function trimKeys(targetObj) {
_.forEach(targetObj, function(value, key) {
if(_.isString(key)){
var newKey = key.trim();
if (newKey !== key) {
targetObj[newKey] = value;
delete targetObj[key];
}
if(_.isArray(targetObj[newKey]) || _.isObject(targetObj[newKey])){
trimKeys(targetObj[newKey]);
}
}else{
if(_.isArray(targetObj[key]) || _.isObject(targetObj[key])){
trimKeys(targetObj[key]);
}
}
});
}
//I stringify this is just to show it in a bad state
var badJson = JSON.stringify(badJson);
console.log(badJson);
//now it is partially fixed with value of string type trimed
badJson = JSON.parse(badJson,function(key,value){
if(typeof value === 'string'){
return value.trim();
}
return value;
});
trimKeys(badJson);
console.log(JSON.stringify(badJson));
注意:我之所以这样做是因为我找不到更好的方法一次性解决所有问题。如果我的代码有问题或者有更好的方法,请与我们分享。谢谢!