且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-30 18:49:28

从你的评论中,


例如,这些内部键将失败
{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,

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

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