Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}}
like image 332
Navin Leon Avatar asked Apr 17 '12 18:04

Navin Leon


2 Answers

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];
}
like image 52
Selvakumar Arumugam Avatar answered Nov 07 '22 04:11

Selvakumar Arumugam


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.

like image 40
jfriend00 Avatar answered Nov 07 '22 04:11

jfriend00