哈希和阵列:性能和实用性之间的妥协\可操作性

时间:2011-03-12 18:14:59

标签: ruby-on-rails ruby arrays json hash

我正在使用Ruby on Rails 3,我想正确处理Web服务响应,找到性能和实用性之间的折衷方案。

我必须决定我的Web服务必须返回到Web客户端应用程序的响应类型。我正在使用JSON来传输数据,我想知道是否更好地使用哈希(对于这些我必须做额外的工作)或数组

例如,我有这样的回应:

[
  {
    "accounts" => {
      [
        "account" => {
          "id"   => 45, 
          "name" => "Test_name45", 
          "..."  => ..."
        }
        "account" => {
          "id"   => 60, 
          "name" => "Test_name60", 
          "..."  => ..."
        }
       ]
     }
   }, 
   {
     "other"  => {
       "sub_other" => {...}
     }
   }
]

我想使用类似的东西(“帐户”中没有数组,从“帐户”到“id”)

  {
    "accounts" => {
      "45" => { 
        "name" => "Test_name45", 
        "..."  => ..."
      }
      "60" => {
        "name" => "Test_name60", 
        "..."  => ..."
      }
   }, 
   {
     "other"  => {
       "sub_other" => {...}
     }
   }

但后者意味着更多的Web服务工作......

如何制作?有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我会使用任何有意义的数据结构。如果您有事物列表,那么使用一个数组,其中每个元素都是的东西。我可能会简化你的数据结构:

{
  "accounts": [
    {
      "id":   45, 
      "name": "Test_name45", 
      "...":  "..."
    },
    {
      "id":   60, 
      "name": "Test_name60", 
      "...":  "..."
    }
  ],
  "other": {
    "sub_other": {"...": "..."}
  }
}

现在,accounts只是一个对象数组 - 无需按键查找内容。在Ruby中,这很好地翻译了:

ruby-1.9.2-p136 :001 > data = JSON.parse(json)
 => {"accounts"=>[{"id"=>45, "name"=>"Test_name45", "..."=>"..."}, {"id"=>60, "name"=>"Test_name60", "..."=>"..."}], "other"=>{"sub_other"=>{"..."=>"..."}}}
ruby-1.9.2-p136 :002 > data["accounts"].each { |acct| puts acct["name"] }
Test_name45
Test_name60
 => [{"id"=>45, "name"=>"Test_name45", "..."=>"..."}, {"id"=>60, "name"=>"Test_name60", "..."=>"..."}]