Makjb lh Makjb lh - 2 months ago 6
JSON Question

How to retrieve all hash keys

This is the hash value:

resource = RestClient::Resource.new 'http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=BMI'
puts response_Json = eval(resource.get)


I can't get get the values recursively for all 'Since' keys.

I tried many solutions on Stack Overflow including accepted answers and tried to modify them.

def extract_list(hash, find_By_Key, collect = false)
if (hash.class == Array) then
hash.each { |value| puts hash; extract_list(value, find_By_Key) }
end
hash.map do |k, v|
puts k.class
v.is_a?(Hash) ? extract_list(v, find_By_Key, (k == find_By_Key)) :
(collect ? v : nil)
v.is_a?(Array) ? extract_list(v, find_By_Key, (k == find_By_Key)) :
(collect ? v : nil)
v.is_a?(Symbol) ? (collect ? v : nil):
(puts v)
end.compact.flatten
end

Answer

Hope this helps!

require 'rest-client'

def extract_list(data, key)
  if data.class == Array
    data.flat_map { |e|
      extract_list(e, key)
    }.compact
  elsif data.class == Hash
    data.flat_map { |k, v|
      if k == key
        v
      else
        extract_list(v, key)
      end
    }.compact
  end
end

resource = RestClient::Resource.new 'http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=BMI'
data = JSON.parse(resource.get)
p extract_list(data, "since")
Comments