JSON.parse changes sorting - Ruby JSON.parse changes sorting - Ruby json json

JSON.parse changes sorting - Ruby


In Ruby 1.8.7 the Hash class does not maintain order either by keys or by order added. If you need something like that, you would need to implement something like ActiveSupport::OrderedHash (http://rubydoc.info/docs/rails/ActiveSupport/OrderedHash)

In Ruby 1.9.x hashes are ordered by when they are inserted by default (see http://www.ruby-doc.org/core/classes/Hash.html)

When you serialize a hash to JSON, all bets are off for maintaining order of your keys. You'll need some post processing after your serialization to ensure order if that's necessary for you.


No, hashmaps are not meant to have a specific ordering. If you need ordering use something different like an array. Or extract all the keys, sort them like you want and then you can have what order you like.

Making assumptions on ordering inside maps is anyway something on which you shouldn't rely, that's the fact.

A good alternative would be to have:

[ [a, aval], [b, bval], ... ]


Jack answered for Ruby, so I'll answer for JSON. From RFC 4627 (emphasis added):

"An object is an unordered collection of zero or more name/value pairs"