Order of keys in a JSON object converted to a Ruby Hash with JSON.parse

In Javascript, object keys are not ordered, whereas in Ruby, Hashes enumerate their values in the order that the corresponding keys were inserted.

In practice, it seems to be the case that when converting JSON objects to Ruby Hashes, keys in the Ruby Hash are in the order in which they were written in the JSON data, e.g.:

irb(main):002:0> JSON.parse('{"a": 1, "b": 2}')
=> {"a"=>1, "b"=>2}

irb(main):005:0> JSON.parse('{"b": 1, "a": 2}')
=> {"b"=>1, "a"=>2}

Can I rely on the assumption that it will always be the case?

I’d think so, because when parsing JSON, I guess the parser is inserting keys as it discovers them, but I couldn’t find any reference on the subject.


Source: ruby

Leave a Reply