Good day to you all,
I've encountered a frustrating issue that seems to happens only in Chrome.
var response = '{"01":"January","02":"February"}',
months = JSON.parse(response);
console.log(months['02']) // undefined in Chrome (my version is 24.0.1312.5 beta)
console.log(months[2]) // "February"
Firefox and Safari seem to handle this as expected, whereas Chrome is casting string-ish JSON keys to integers.
jQuery's parseJSON method has the same behaviour (I'm assuming it relies on the browser's JSON.parse method).
I'm fairly tied down to this specific API response format, so I'd rather not change the server's response. Is there a sane way to force Chrome to behave as expected?
"Is there a sane way to force Chrome to behave as expected?"
Not sure if you call this sane, but you can do some manipulation in a reviver function to patch it.
var response = '{"01":"January","02":"February"}',
months = JSON.parse(response,
function(k,v) {
if (this.constructor === Object && // is Object
!isNaN(k) && // key is a Number
+k > 0 && // from 1
+k < 1 && // to 9
k.charAt(0) !== '0') { // missing the '0'
this['0' + k] = v; // manually assign the key
return; // return undefined to prevent assignment
}
return v; // allow the assignment
});
console.log(months['02']);
Of course you'll likely need to tweak it a bit for your code so that you're not fixing things that don't need to be fixed.
You'll probably also want to test the browser before it runs to see if the fix is needed.
var needsJSONfix = !JSON.parse('{"01":1}')["01"];
months = JSON.parse(response, needsJSONfix ? fixFunc : null);
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