I have some JSON data but all the keys are in UPPER case. How to parse them and convert the keys to lower? I am using jQuery.
for example:
JSON data:
{"ID":1234, "CONTENT":"HELLO"}
Desired output:
{id:1234, content:"HELLO"}
SQL, by default, is case insensitive to identifiers and keywords, but case sensitive to data. JSON is case sensitive to both field names and data.
The JSON syntax does not impose any restrictions on the strings used as names,... There is no standard naming of keys in JSON and that camelCase or snake_case should work fine.
JSON is case-sensitive. SQL is case-insensitive, but names in SQL code are implicitly uppercase.
JSON. parse() is a crucial method for converting JSON data in string form into Javascript objects. It is possible to convert simple or complex objects, but you should never convert calculations or code, like for loops.
How about this:
json.replace(/"([^"]+)":/g,function($0,$1){return ('"'+$1.toLowerCase()+'":');}));
The regex captures the key name $1 and converts it to lower case.
Live demo: http://jsfiddle.net/bHz7x/1/
[edit] To address @FabrícioMatté's comment, another demo that only matches word characters: http://jsfiddle.net/bHz7x/4/
Iterate over the properties and create lowercase properties while deleting old upper case ones:
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
Or you can just build a new object from the old one's properties:
var obj = $.parseJSON(str),
lowerCased = {};
$.each(obj, function(i, v) {
lowerCased[i.toLowerCase()] = v;
});
Fiddle
jQuery.each
String.toLowerCase
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With