From: Matthew Kerwin Date: 2013-03-12T06:14:58+09:00 Subject: Re: Access values for JSON.parse response Nicole Villette wrote in post #1101133: > Hello, Does anyone know [how] to get the values from a nested hash in > Ruby. Yep. > I made the following request which after doing the JSON.parse, it > returns a nested hash with arrays. So, I am trying to figure out how to > access the values in the response. See below for response. Since your "parsed" object is a Hash, you can access the first level of nesting with: parsed['TOD'] which returns a Hash, so you can access the next level with: parsed['TOD']['AdBreaks'] and so on. At some point in your structure there's an Array instead of a Hash, so you'd need to use something like: parsed['TOD']['AdBreaks']['AdBreak'][0]['duration'] # or parsed['TOD']['AdBreaks']['AdBreak'].first['duration'] But personally I'd probably go for one of the following: parsed['TOD']['AdBreaks']['AdBreak'].map{|ad| ad['duration'] } # or parsed['TOD']['AdBreaks']['AdBreak'].any?{|ad| ad['duration'] == 30 } # or parsed['TOD']['AdBreaks']['AdBreak'].select{|ad| ad['duration'] == 30 } Also note: this is yucky. Yucky yucky yucky. A saner person might use some local variables. Even one will help a lot: adbreaks = parsed['TOD']['AdBreaks']['AdBreak'] # while I'm here: why does 'AdBreaks' hold one item, # but 'AdBreak' hold an array? Odd. lengths_of_breaks = adbreaks.map {|ad| ad['duration'] } list_of_30s_breaks = adbreaks.select {|ad| ad['duration'] == 30 } # etc. -- Posted via http://www.ruby-forum.com/.