Navin Leon Navin Leon - 3 months ago 10
Javascript Question

Change JSON key names (to all capitalized) recursively?

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

Answer

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

enter image description here


A simple loop should do the trick,

DEMO

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