有没有办法将所有
JSON密钥名称更改为大写字母?
例如:{“name”:“john”,“Age”:“21”,“sex”:“male”,“place”:{“state”:“ca”}}
并需要转换为
{ “NAME”: “约翰”,“AGE”: “21”,“性别”: “男”,“地点”:{ “STATE”: “CA”}}
谢谢你的建议.
-Navin
解决方法
从你的评论,
eg like these will fail for the inner keys
{“name”:”john”,”Age”:”21″,”sex”:”male”,”place”:{“state”:”ca”}}
您可能需要对此类情况使用递归.见下文,
DEMO
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;
}
产量
一个简单的循环应该可以做到,
DEMO
var output = {};
for (i in obj) {
output[i.toupperCase()] = obj[i];
}