From: Matthew Kerwin Date: 2013-03-13T08:58:50+09:00 Subject: Re: Access values for JSON.parse response Nicole Villette wrote in post #1101285: > Joel Pearson wrote in post #1101264: >> There's probably a simpler way to lay this out, but this worked for me: >> irb(main):022:0> recursive_find 'duration', h >> => 30 > > Joel, > > I do have one question for you. What happens when there are duplicate > names in the response. For ex. duration and uri appear in different > arrays, so how would you specify which one you want? Well, one way I thought of was to have it do a select instead of a find (i.e. return all the matches, not just the first). To make it useful, I had it return the path to the value as well as the value itself. def recursive_select( key, object, path=[] ) matches = [] case object when Array object.each_with_index do |el, i| if el.is_a?(Hash) || v.is_a?(Array) res = recursive_select( key, el, path+[i] ) matches += res if res end end when Hash matches << {'path'=>path+[key], 'value'=>object[key]} if object.has_key? key object.each do |k,v| if v.is_a?(Hash) || v.is_a?(Array) res = recursive_select( key, v, path+[k] ) matches += res if res end end end matches.any? ? matches : nil end irb(main):005:0> recursive_select 'duration', h => [{"path"=>["TOD", "AdBreaks", "AdBreak", 0, "duration"], "value"=>30}, {"path"=>["TOD", "AdBreaks", "AdBreak", 0, "Ad", 0, "duration"], "value"=>30}] -- Posted via http://www.ruby-forum.com/.