简体   繁体   English

递归更改JSON密钥名称(全部大写)?

[英]Change JSON key names (to all capitalized) recursively?

Is there a way to change all JSON key names to capital letter ? 有没有办法将所有JSON密钥名称更改为大写字母?

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"}}

From your comment, 从你的评论,

eg like these will fail for the inner keys {"name":"john","Age":"21","sex":"male","place":{"state":"ca"}} 例如,这些内部键将失败{“name”:“john”,“Age”:“21”,“sex”:“male”,“place”:{“state”:“ca”}}

You may need to use recursion for such cases. 您可能需要对此类情况使用递归。 See below, 见下文,

DEMO 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;
}

Output 产量

在此输入图像描述


A simple loop should do the trick, 一个简单的循环应该可以做到,

DEMO DEMO

var output = {};
for (i in obj) {
   output[i.toUpperCase()] = obj[i];
}

You can't change a key directly on a given object, but if you want to make this change on the original object, you can save the new uppercase key and remove the old one: 您不能直接在给定对象上更改密钥,但如果要对原始对象进行此更改,则可以保存新的大写密钥并删除旧密钥:

 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)); 

FYI, this function also protects again inadvertently modifying inherited enumerable properties or methods. 仅供参考,此功能还可以再次保护无意中修改继承的可枚举属性或方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM