最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change JSON key names (to all capitalized) recursively? - Stack Overflow

programmeradmin3浏览0评论

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

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"}}
Share Improve this question edited Aug 19, 2019 at 8:27 Vadim Kotov 8,2848 gold badges50 silver badges63 bronze badges asked Apr 17, 2012 at 18:18 Navin LeonNavin Leon 1,1665 gold badges22 silver badges45 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 17

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

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.

发布评论

评论列表(0)

  1. 暂无评论