哪个组件正在对 Rails JSON 响应中的 JSON 值进行排序,为什么? [英] Which component is sorting JSON values in Rails JSON response and why?

查看:34
本文介绍了哪个组件正在对 Rails JSON 响应中的 JSON 值进行排序,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 Rails JSON 输出是按字母顺序排序的.

I noticed Rails JSON output is alphabetically sorted.

这是来自基本 Rails 应用的示例 JSON 输出:

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"}

似乎 created_atupdated_at 具有相同的起源,并且可能应该彼此相邻.但是 Rails 输出是按字母顺序排序的.

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?

推荐答案

我发现 ActiveModel::Serializers::JSON#as_json 的第一行调用了 ActiveModel::Serialization#serializable_hash,其中有这行代码对属性名称进行排序:

I found that the first line of ActiveModel::Serializers::JSON#as_json calls ActiveModel::Serialization#serializable_hash, which has this line of code that sorts the attribute names:

attribute_names = attributes.keys.sort

这是对属性进行排序的地方.至于为什么对它们进行排序,答案不太清楚.Josh Peek 在 2009 年 7 月以这种提交方式引入了排序,但提交注释只是将 AMo JSON 序列化程序集成到 AR 中".他没有说明为什么将调用添加到 .sort.

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.

但是,如果您不喜欢这种类型,那么只要您愿意在 Rails 4 发布时升级到它,那您就走运了.Rails 核心团队似乎同意不应该对 JSON 键进行排序.2012 年 3 月,他们接受了这个拉取请求,其中对 sort 的调用是删除.此提交不在最新的 Rails 3.2 中,但会在即将推出的 Rails 4 中.

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 sort was removed. This commit is not in the latest Rails 3.2 but will be in Rails 4, which is coming soon.

这篇关于哪个组件正在对 Rails JSON 响应中的 JSON 值进行排序,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆