1

Json string:

"{"detail":{"01":0,"02":0,"03":0,"04":0,"05":"-","06":"-","07":"-","08":"-","09":"-","10":"-","11":"-","12":"-"}}"

jQuery.parseJSON result:

{detail:{10:"-", 11:"-", 12:"-", '01':0, '02':0, '03':0, '04':0, '05':"-", '06':"-", '07':"-", '08':"-", '09':"-"}}

I do not know why parseJSON changes the order of keys (10, 11, 12, 01, 02,... instead of 01,02,03,...). How can I keep the order in this case?

Nghi Ho
  • 463
  • 1
  • 6
  • 18

1 Answers1

1

I do not know why parseJSON changes the order of keys (10, 11, 12, 01, 02,... instead of 01,02,03,...).

Most browsers iterate over properties in the following order:

  • integer indexes(*) in ascending order
  • strings in creation order

*: A positive 32-bit integer is considered to be an integer index

However, is is implementation specific and not required by the language standard. There are likely environments that have a completely different behavior.

(Related: Does ES6 introduce a well-defined order of enumeration for object properties?)

So 10, 11, 12 are listed first because they are integers. 01, 02, etc are following because they are treated as strings.

How can I keep the order in this case?

You cannot. You have to use an array, which should be rather trivial in your case since your keys are basically consecutive numbers.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143