Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent automatic JSON key type-casting

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?

like image 530
sheldonbaker Avatar asked Nov 10 '12 20:11

sheldonbaker


1 Answers

"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);
like image 134
I Hate Lazy Avatar answered Nov 05 '22 16:11

I Hate Lazy