2013-05-10 63 views
1

在我的代码,我解析一个JSON对象,像 [{"name":"karthi"},{"name":"shreshtt"},{"name":"jitu"},{"name":null},{"name":null},{"name":null},{"name":null}]如何使用json在一个数组对象中获取整个数组的名称?

在此,我要收集所有的名字在单个阵列对象。这是我的控制器现在的外观。我想将结果名称数组存储在@hotels变量中。

controller.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 

视图/旅馆住宿/ index.json.erb

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

什么是你的'Hotel.all'回报?如果您可以为“酒店”模型提供模式,这可能会很有用。 – Kashyap 2013-05-10 12:22:55

+0

你能给出预期的输出吗?它是怎样的? – 2013-05-10 12:49:45

+0

@Priti { “家”:[{名称:karthick},{ “名”: “shreshtt”}]}我需要这样的分析,如何在我从那里' “酒店”'就要代码 – 2013-05-10 12:55:17

回答

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"] 
+0

你没有得到我的观点没有纨绔子弟,这是名称的解析现在[ { “名”: “卡” }, { “名”: “shreshtt” }]我想是{ “酒店”: { “名”: “卡” }, { “名称”: “shreshtt” },]}这样我想 – 2013-05-10 12:25:03

+0

A = [{名: “卡”},{名称: “shreshtt”},{名称: “激凸”},{名称:无}, {name:nil},{name:nil},{name:nil}],hotels = Hash.new,hotels = {:hotel => a} – 2013-05-10 12:44:36

+0

酒店的输出将为: {:hotel => [{:name =>“karthi”},{:name =>“shreshtt”},{:name =>“jitu”},{:name => nil},{:name => nil },{:name => nil},{:name => nil}]} – 2013-05-10 12:46:55

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"}]} 
0

你可以像下面

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

format.json { render json: json_obj } 
+0

我必须在控制器中编写此代码是否正确?,我必须在json.erb中进行其他更改吗?花花公子 – 2013-05-10 12:45:31

+0

我不认为你将不得不写json.erb更多 – jbmyid 2013-05-10 12:48:23

+0

那么这段代码就足够了,我只好独自编写此代码在控制器,它是确定 – 2013-05-10 12:52:49

相关问题