Rails traverse deep array of hashes

一个人想着一个人 提交于 2019-12-23 01:11:18

问题


I got this very confusing array of hashes as an API response.

http://jsfiddle.net/PP9N5/

( the full response is massive. Posting only a part of it but it covers all elements of the response) How can I get to "airlines".

I tried this

<% @flight["air_search_result"]["onward_solutions"]["solution"].each do|h| %>
  <strong><%=h["pricing_summary"]["total_fare"] %></strong> - 
  <% h["flights"]["flight"]["segments"]["segment"].each do |s| %>
    <%= s['airline'] %>
  <% end %> <br> <hr>
<% end %>

And I get this error

can't convert String into Integer

I did some modifications like

<%= h["flights"]["flight"]["segments"]["segment"].first["airline"] %>
Error received - can't convert String into Integer

and

<%= h["flights"]["flight"]["segments"]["segment"][0]["airline"] %>
Error received - undefined method '[]' for nil:NilClass

Isnt there a simple way, like I say to find a key "airline" and for that key it returns its value. I stumbled upon this link, though I dont get any error, I also dont get any result.

Thanks.

UPDATE

I did this

<% h["flights"]["flight"]["segments"]["segment"].each do |o,p| %>
<% if o=="airline" %> <%= p %> <% end %>
 <% end %> <br> <hr>
<% end %>

I can get few values of airlines where inside segment there is no array.
For eg, i can get where departure_date_time is 2014-07-07T07:10:00, index = 5.

http://jsfiddle.net/PP9N5/1/ (scroll down)


回答1:


Here is some code you can add which will extract all keys equal the parameter in any Hash within your Hash:

class Hash
  def deep_find(query, &block)
    flat_map do |key, value|
      if key == query
        yield value if block_given?
        [value]
      elsif value.is_a? Hash
        value.deep_find(query, &block)
      elsif value.is_a? Array
        value.select { |i| i.is_a? Hash }.flat_map { |h| h.deep_find(query, &block) }
      end
    end
  end
end

Example:

hash = {"h" => [{ 'x' => [1, 5] }, { 'x' => 2 }, { 'f' => { 'x' => [3, 4] } }], 'x' => 6 }
hash.deep_find('x') { |x| puts "#{x}" }
# [1, 5]
# 2
# [3, 4]
# 6
# => [[1, 5], 2, [3, 4], 6]



回答2:


it's a tipical problem :D

Replace "=>" for ":" and render.

your_json = {.....}
your_json.gsub("=>", ":")
puts your_json

You can validate a JSON before to work it with http://jsonlint.com/.



来源:https://stackoverflow.com/questions/24579053/rails-traverse-deep-array-of-hashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!