2013-02-03 24 views
1

我注意到Rails的JSON輸出按字母順序排序。哪個組件在Rails JSON響應中排序JSON值?爲什麼?

這是一個基本的Rails應用程序的示例輸出JSON:

{"created_at":"2013-02-03T19:44:39Z","email":"[email protected]","id":2,"name":"Mohsen","updated_at":"2013-02-03T19:44:39Z"} 

看來created_atupdated_at具有相同的起源,或許應該來彼此相鄰。但Rails輸出按字母順序排序。

哪個組件正在做這項工作,爲什麼?

+0

是因爲OrderedHash還是因爲你使用ruby <1.9?我不確定發生了什麼,但這裏是Rails json編碼的來源。 https://github.com/mateusg/docrails_pt-BR/blob/master/activesupport/lib/active_support/json/encoding.rb –

+0

你使用的是Ruby 1.9嗎? –

回答

3

我發現ActiveModel::Serializers::JSON#as_json第一行調用ActiveModel::Serialization#serializable_hash,其中有this line of code that sorts the attribute names

attribute_names = attributes.keys.sort 

這是屬性進行排序。至於爲什麼他們排序,答案不太清楚。 Josh Peek introduced the sort in this commit way back in July of 2009,但提交評論只是「將AMo JSON串行器集成到AR中」。他沒有說明他爲什麼加入電話.sort

但是,如果您不喜歡這種類型,只要您願意升級到Rails 4,就會運氣好。 Rails核心團隊似乎同意不應對JSON密鑰進行排序。 In March of 2012 they accepted this pull request in which the call to sort was removed。這個提交不在最新的Rails 3.2中,但將在即將推出的Rails 4中。