我在Rails控制器中有一个哈希,如下所示:
{
"-35": 10,
"-16": 97,
"-4": 205,
"0": 825,
"12": 116,
"13": 93,
"19": 112,
"30": 77
}
其键从最低到最高编号。当我调用一个产生JSON的路由时,我得到以下输出:
{
"0": 825,
"12": 116,
"13": 93,
"19": 112,
"30": 77,
"-35": 10,
"-16": 97,
"-4": 205
}
Rails在渲染过程中更改顺序。
如何防止这种情况发生?
答案 0 :(得分:0)
我认为,默认情况下不进行排序。如果使用json格式化程序,默认情况下它会为您执行。
我在httpie,curl和浏览器上测试过。
render json: obj, status: :ok
<强> Httpie 强>
#Input => Output
#Content-Type: application/json; charset=utf-8
http URL => {
"-16": 97,
"-35": 10,
"-4": 205,
"0": 825,
"12": 116,
"13": 93,
"19": 112,
"30": 77
}
http --pretty=none URL =>
{"-35":10,"-16":97,"-4":205,"0":825,"12":116,"13":93,"19":112,"30":77}
<强>卷曲强>
#Input => Output
#Content-Type: application/json; charset=utf-8
curl http://lvh.me:3000/test =>
{"-35":10,"-16":97,"-4":205,"0":825,"12":116,"13":93,"19":112,"30":77}
RestClient Gem
RestClient.get(URL).body =>
"{\"-35\":10,\"-16\":97,\"-4\":205,\"0\":825,\"12\":116,\"13\":93,\"19\":112,\"30\":77}"
#no matter what returns as a string
但是如果要改变普通:render :plain => obj.to_json, status: :ok
RestClient,Curl和HTTPie返回相同的值,但浏览器除外:)
只是内容类型不同Content-Type: text/plain; charset=utf-8
结论:
据我所知,rails默认不排序......