递归更改JSON密钥名称(全部大写)? [英] Change JSON key names (to all capitalized) recursively?
问题描述
有没有办法将所有JSON密钥名称更改为大写字母?
例如: {name:john,年龄:21,性别:男性,地点:{州:ca}}
并且需要转换为
{NAME:john,AGE:21,SEX:男性,PLACE:{状态:ca}}
谢谢你的推荐。
-Navin
从你的评论中,
例如,这些内部键将失败
{name:john,Age:21,sex:male, place:{state:ca}}
您可能需要对此类情况使用递归。见下文,
var output = { };
for(i in obj){
output [i.toUpperCase()] = obj [i];
}
Is there a way to change all JSON key names to capital letter ?
eg: {"name":"john","Age":"21","sex":"male","place":{"state":"ca"}}
and need to be converted as
{"NAME":"john","AGE":"21","SEX":"male","PLACE":{"STATE":"ca"}}
Thanks in advamnce.
-Navin
From your comment,
eg like these will fail for the inner keys {"name":"john","Age":"21","sex":"male","place":{"state":"ca"}}
You may need to use recursion for such cases. See below,
var output = allKeysToUpperCase(obj);
function allKeysToUpperCase(obj) {
var output = {};
for (i in obj) {
if (Object.prototype.toString.apply(obj[i]) === '[object Object]') {
output[i.toUpperCase()] = allKeysToUpperCase(obj[i]);
} else {
output[i.toUpperCase()] = obj[i];
}
}
return output;
}
Output
A simple loop should do the trick,
var output = {};
for (i in obj) {
output[i.toUpperCase()] = obj[i];
}
这篇关于递归更改JSON密钥名称(全部大写)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!