有没有办法将所有 JSON 键名更改为大写字母?
例如:
{"name":"john","Age":"21","sex":"male","place":{"state":"ca"}}
并且需要转换为
{"NAME":"john","AGE":"21","SEX":"male","PLACE":{"STATE":"ca"}}
有没有办法将所有 JSON 键名更改为大写字母?
例如:
{"name":"john","Age":"21","sex":"male","place":{"state":"ca"}}
并且需要转换为
{"NAME":"john","AGE":"21","SEX":"male","PLACE":{"STATE":"ca"}}
从你的评论来看,
例如,对于内部键 {"name":"john","Age":"21","sex":"male","place":{"state":"ca"}},像这样会失败
对于这种情况,您可能需要使用递归。见下文,
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;
}
输出
一个简单的循环应该可以解决问题,
var output = {};
for (i in obj) {
output[i.toUpperCase()] = obj[i];
}
您不能直接在给定对象上更改键,但如果要对原始对象进行此更改,可以保存新的大写键并删除旧键:
function changeKeysToUpper(obj) {
var key, upKey;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
upKey = key.toUpperCase();
if (upKey !== key) {
obj[upKey] = obj[key];
delete(obj[key]);
}
// recurse
if (typeof obj[upKey] === "object") {
changeKeysToUpper(obj[upKey]);
}
}
}
return obj;
}
var test = {"name": "john", "Age": "21", "sex": "male", "place": {"state": "ca"}, "family": [{child: "bob"}, {child: "jack"}]};
console.log(changeKeysToUpper(test));
仅供参考,此功能还可以再次保护无意中修改继承的可枚举属性或方法。