递归更改JSON密钥名称(全部大写)? [英] Change JSON key names (to all capitalized) recursively?

查看:70
本文介绍了递归更改JSON密钥名称(全部大写)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将所有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,

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

这篇关于递归更改JSON密钥名称(全部大写)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆