I noticed Rails JSON output is alphabetically sorted.
This is a sample JSON output from a basic Rails app:
{"created_at":"2013-02-03T19:44:39Z","email":"mohsen@example.com","id":2,"name":"Mohsen","updated_at":"2013-02-03T19:44:39Z"}
It seems created_at and updated_at have same origin and probably should come next to each other. But Rails output is alphabetically sorted.
Which component is doing this work and why?
I found that the first line of
ActiveModel::Serializers::JSON#as_jsoncallsActiveModel::Serialization#serializable_hash, which has this line of code that sorts the attribute names:This is where the attributes are sorted. As for why they are sorted, the answer is less clear. Josh Peek introduced the sort in this commit way back in July of 2009, but the commit comment was simply “Integrate AMo JSON serializer into AR.” He didn’t say why he added the call to
.sort.But if you don’t like the sort, you’re in luck as long as you’re willing to upgrade to Rails 4 when it comes out. The Rails core team seems to agree that the JSON keys shouldn’t be sorted. In March of 2012 they accepted this pull request in which the call to
sortwas removed. This commit is not in the latest Rails 3.2 but will be in Rails 4, which is coming soon.