如何在Rails中访问JSON? [英] How to access JSON in Rails?

查看:97
本文介绍了如何在Rails中访问JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON参数.

I have the following JSON params.

Started POST "/tickets/move.json" for ::1 at 2015-01-30 15:30:13 -0600
Processing by TicketsController#move as JSON
  Parameters: {"_json"=>[{"id"=>"1", "col"=>1, "row"=>1}, {"id"=>"2", "col"=>2, "row"=>2}, {"id"=>"3", "col"=>2, "row"=>1}, {"id"=>"4", "col"=>4, "row"=>1}, {"id"=>"5", "col"=>5, "row"=>1}], "ticket"=>{}}

如何像使用常规rails params一样访问它们?

How can I access them, as I would with regular rails params?

推荐答案

这是常规的params哈希. Rails通常很聪明,可以为您解码JSON请求并将结果对象放置在params中,并且哈希火箭(=>)是一个死胡同,因为它是Ruby哈希而不是JSON.格式更好,看起来像这样:

That's a regular params hash. Rails is usually smart enough to decode a JSON request and put the resulting object in params for you, and the hashrockets (=>) are a dead giveaway that it's a Ruby hash and not JSON. Formatted more nicely it looks like this:

{ "_json"  => [ { "id" => "1", "col" => 1, "row" => 1 },
                { "id" => "2", "col" => 2, "row" => 2 },
                # ...
              ],
  "ticket" => {}
}

您将像其他哈希一样访问它:

You'll access it like any other Hash:

p params["_json"]
# => [ {"id"=>"1", "col"=>1, "row"=>1},
#      {"id"=>"2", "col"=>2, "row"=>2},
#      ...
#    ]

p params["_json"][0]
# => {"id"=>"1", "col"=>1, "row"=>1}

p params["_json"][0]["id"]
# => "1"

p params["ticket"]
# => {}

实际上,它应该是HashWithIndifferentAccess,所以您也应该能够使用符号键:

It ought to be a HashWithIndifferentAccess, actually, so you should be able to use symbol keys as well:

p params[:_json][0][:id]
# => "1"

这篇关于如何在Rails中访问JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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