How to parse JSON for a lowercase object

I have some JSON data, but all the keys are in the UPPER folder. How to disassemble them and convert keys to lower ones? I am using jQuery.

eg:

JSON data:

{"ID":1234, "CONTENT":"HELLO"}

Required Conclusion:

{id:1234, content:"HELLO"}
+5
source share
4 answers

How about this:

json.replace(/"([^"]+)":/g,function($0,$1){return ('"'+$1.toLowerCase()+'":');}));

The regular expression captures the key name $ 1 and converts it to lowercase.

Live demo: http://jsfiddle.net/bHz7x/1/

[edit] To post a comment @ FabrícioMatté, another demo that matches only word characters: http://jsfiddle.net/bHz7x/4/

+9
source

Iterate over properties and create lowercase properties when deleting old upper case:

var str = '{"ID":1234, "CONTENT":"HELLO"}';

var obj = $.parseJSON(str);
$.each(obj, function(i, v) {
    obj[i.toLowerCase()] = v;
    delete obj[i];
});

console.log(obj);
//{id: 1234, content: "HELLO"} 

Fiddle

:

var obj = $.parseJSON(str),
    lowerCased = {};
$.each(obj, function(i, v) {
    lowerCased[i.toLowerCase()] = v;
});

Fiddle

:

+5

This is the function:

function JSON_Lower_keys(J) {
   var ret={};
   $.map(JSON.parse(J),function(value,key){
             ret[key.toLowerCase()]=value;
   })
   return ret;
}

which is the call:

console.log(JSON_Lower_keys('{"ID":1234, "CONTENT":"HELLO"}'))
0
source

You can use js and use Objeck.keys ()

var oldObj = { "ID":123, "CONTENT":"HI" }
var keysUpper = Object.keys(oldObj)
var newObj = {}
for(var i in keysUpper){
   newObj[keysUpper[i].toLowerCase()] = oldObj[keysUpper[i]]
}
console.log(JSON.stringify(newObj))

Copy and paste in the console of your browser (F12) → the output: {"id": 123, "content": "HI"}

0
source

All Articles