Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON to object with lower case key

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"}
like image 764
SwiftMango Avatar asked Feb 04 '13 23:02

SwiftMango


People also ask

Should JSON keys be lower case?

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.

Should JSON keys be capitalized?

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.

Is JSON key case sensitive?

JSON is case-sensitive. SQL is case-insensitive, but names in SQL code are implicitly uppercase.

Can you JSON parse an object?

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.


2 Answers

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/

like image 169
Christophe Avatar answered Sep 23 '22 07:09

Christophe


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

References:

  • jQuery.each
  • String.toLowerCase
like image 33
Fabrício Matté Avatar answered Sep 22 '22 07:09

Fabrício Matté