3

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?

JC Ford
  • 6,946
  • 3
  • 25
  • 34
  • I don't have access to the web service, so I can't fix it there. – JC Ford Oct 01 '15 at 22:54
  • 1
    This is a better answer to your problem then the one in the duplicate - http://stackoverflow.com/a/5480605/5157454 – Ori Drori Oct 01 '15 at 23:10
  • Voting to reopen because the other question is about changing the case of the properties of an existing object, and this one is about deserializing JSON. – Oriol Oct 01 '15 at 23:22

2 Answers2

4

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.

Oriol
  • 274,082
  • 63
  • 437
  • 513
2

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];
}
gmast
  • 192
  • 8