1

在我的代码中,我正在解析一个 JSON 对象,例如 [{"name":"karthi"},{"name":"shreshtt"},{"name":"jitu"},{"name":null},{"name":null},{"name":null},{"name":null}]

在此,我想在单个数组对象中收集所有名称。这就是我的控制器现在的样子。我想将结果名称数组存储在@hotels变量中。

控制器.erb

respond_to :json, :xml
  def index
    @hotels = Hotel.all

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @hotels.to_json(:only => [ :name ]) }
    end
  end

查看/hoels/index.json.erb

[ 
hotel: <% @hotels.each do |hotel| %>
    { 'name': "<%= hotel.name.to_json.html_safe %>" }
     <% unless index== @hotels.count - 1%>
  <% end %>
   <% end %>
]
4

3 回答 3

0

那是怎么回事?

a = {}
a["hotel"] = []
array = [{"name"=>"kathi"}, {"name"=>"kathi2"}, {"name"=>"kathi3"}, {"name"=>"kathi4"}, {"name" => nil}]
a["hotel"] = array
a["hotel"].each do |v|
  if v["name"] == nil
    a["hotel"].delete(v)
  end
end
a => {"hotel"=>[{:name=>"kathi"}, {:name=>"kathi2"}, {:name=>"kathi3"}, {:name=>"kathi4"}]}  
于 2013-05-10T12:27:12.103 回答
0

您只想将名称添加到数组中吗?怎么样:

a = [{name: "karthi"},{name: "shreshtt"},{name: "jitu"},{name: nil},{name: nil},{name: nil},{name: nil}]
@hotel = []
a.collect{|a_name| @hotel << a_name[:name]}
=> ["karthi", "shreshtt", "jitu", nil, nil, nil, nil]
@hotel.compact!
=> ["karthi", "shreshtt", "jitu"]
于 2013-05-10T12:22:54.737 回答
0

你可以这样做

hotels = Hotel.select("name").where("name is not NULL")
json_obj = {hotels: hotels}.to_json

format.json { render json: json_obj }
于 2013-05-10T12:43:30.610 回答