gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中访问 JSON?

转载 作者:行者123 更新时间:2023-12-04 07:33:14 26 4
gpt4 key购买 nike

我有以下 JSON 参数。

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 哈希。 Rails 通常足够聪明,可以解码 JSON 请求并将结果对象放入 params 中,而 hashrockets ( => ) 是一个致命的赠品,它是 Ruby 哈希而不是 JSON。格式化得更漂亮,它看起来像这样:

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

您将像访问任何其他哈希一样访问它:
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,因此您也应该能够使用符号键:
p params[:_json][0][:id]
# => "1"

关于ruby-on-rails - 如何在 Rails 中访问 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28245039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com