Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to convert property names to lower case when deserializing a JSON object?

I don't have control of the web service I'm calling. It returns JSON with capitalized property names. This bothers me.

Are there any Angular plugins that will fix this? Or is there an easy and efficient way of doing so in javascript?

like image 920
JC Ford Avatar asked Oct 30 '25 10:10

JC Ford


2 Answers

You can use pass a reviver function as an argument to JSON.parse:

JSON.parse('{"Test": {"Foo": 1, "Bar": 2} }', function(prop, value) {
  var lower = prop.toLowerCase();
  if(prop === lower) return value;
  else this[lower] = value;
});

Basically, it converts each property to lower case, and checks if it's different. If it is different, it sets the lowercase property and returns undefined, thus removing the non-lowercase one. If they are equal, it returns the value, so nothing special is done.

like image 111
Oriol Avatar answered Nov 01 '25 23:11

Oriol


Javascript Object class has a method called keys(). You can use it to iterate through your object property names and to edit them using toLowerCase() after you've converted the JSON string to a javascript object.

var obj = {"Test": "foo"};
var ar = Object.keys(obj);
for(var i = 0; i < ar.length; i++){
    var upperCasePropertyName = ar[i];
    ar[i] = ar[i].toLowerCase();
    obj[ar[i]] = obj[upperCasePropertyName];
    delete obj[upperCasePropertyName];
}
like image 31
gmast Avatar answered Nov 01 '25 22:11

gmast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!