tomwoods tomwoods - 1 year ago 51
Ajax Question

How can I prevent jQuery's $.getJSON from converting my ajax response keys from strings to integers?

I'm trying to use a JSON response object that is ordered by email to populate a select box, but JQuery seems to be changing the type of the key from text to integer, thus re-ordering the response object by the now numeric index, screwing up the order of the select box.

So a json response like:


after a code similar to:


outputs an object like this:


How can I prevent this conversion / reordering?

P.s. this also happens with $.ajax

Answer Source

Two things are wrong here.

1) JSON keys are always string. Just because it is written without quotes doesn't make it a number. It just means the key name is "safe", i.e. doesn't contain spaces or other special characters.

2) JSON hash keys absolutely not guaranteed to be in any particular order. If you are expecting them to be, then your expectation is wrong. You should be serializing your data as an array of objects (or strings) instead of a single hash object.



[{key:1,value:""},{key:2, value:""}]

Actually make that three things

3) The output you seeing has nothing to do with jQuery. That is just how console.log() serialized hash object you gave to it. Which is valid (see #2).