Ruby:将嵌套 Ruby 哈希转换为非嵌套哈希

2023-12-25

现在,我有一个服务器调用返回以下 Ruby 哈希值:

{
  "id"=>"-ct",
  "factualId"=>"",
  "outOfBusiness"=>false,
  "publishedAt"=>"2012-03-09 11:02:01",
  "general"=>{
    "name"=>"A Cote",
    "timeZone"=>"EST",
    "desc"=>"À Côté is a small-plates restaurant in Oakland's charming
            Rockridge district. Cozy tables surround large communal tables in both
            the main dining room and on the sunny patio to create a festive atmosphere.
              Small plates reflecting the best of seasonal Mediterranean cuisine are served
            family-style by a friendly and knowledgeable staff.\nMenu items are paired with
            a carefully chosen selection of over 40 wines by the glass as well as a highly
            diverse bottled wine menu. Specialty drinks featuring fresh fruits, rare
            botaniques and fine liqueurs are featured at the bar.",
    "website"=>"http://acoterestaurant.com/"
  },
  "location"=>{
    "address1"=>"5478 College Ave",
    "address2"=>"",
    "city"=>"Oakland",
    "region"=>"CA",
    "country"=>"US",
    "postcode"=>"94618",
    "longitude"=>37.84235,
    "latitude"=>-122.25222
  },
  "phones"=>{
    "main"=>"510-655-6469",
    "fax"=>nil
  },
  "hours"=>{
    "mon"=>{"start"=>"", "end"=>""},
    "tue"=>{"start"=>"", "end"=>""},
    "wed"=>{"start"=>"", "end"=>""},
    "thu"=>{"start"=>"", "end"=>""},
    "fri"=>{"start"=>"", "end"=>""},
    "sat"=>{"start"=>"", "end"=>""},
    "sun"=>{"start"=>"", "end"=>""},
    "holidaySchedule"=>""
  },
  "businessType"=>"Restaurant"
}

它有几个嵌套的属性,例如:

"wed"=>{"start"=>"", "end"=>""}

我需要将此对象转换为 Ruby 中的非嵌套哈希。理想情况下,我想检测属性是否嵌套,并做出相应的响应,即当它确定属性 'wed' 是嵌套的,它提取数据并存储在字段中 'wed-start' and 'wed-end',或类似的东西。

有人对如何开始有任何建议吗?


编辑:稀疏宝石 https://rubygems.org/gems/sparsify被发布作为该问题的通用解决方案。


这是我几个月前完成的一个实现。您需要将 JSON 解析为哈希,然后使用 Sparsify 来稀疏哈希。

# Extend into a hash to provide sparse and unsparse methods. 
# 
# {'foo'=>{'bar'=>'bingo'}}.sparse #=> {'foo.bar'=>'bingo'}
# {'foo.bar'=>'bingo'}.unsparse => {'foo'=>{'bar'=>'bingo'}}
# 
module Sparsify
  def sparse(options={})
    self.map do |k,v|
      prefix = (options.fetch(:prefix,[])+[k])
      next Sparsify::sparse( v, options.merge(:prefix => prefix ) ) if v.is_a? Hash
      { prefix.join(options.fetch( :separator, '.') ) => v}
    end.reduce(:merge) || Hash.new
  end
  def sparse!
    self.replace(sparse)
  end

  def unsparse(options={})
    ret = Hash.new
    sparse.each do |k,v|
      current = ret
      key = k.to_s.split( options.fetch( :separator, '.') )
      current = (current[key.shift] ||= Hash.new) until (key.size<=1)
      current[key.first] = v
    end
    return ret
  end
  def unsparse!(options={})
    self.replace(unsparse)
  end

  def self.sparse(hsh,options={})
    hsh.dup.extend(self).sparse(options)
  end

  def self.unsparse(hsh,options={})
    hsh.dup.extend(self).unsparse(options)
  end

  def self.extended(base)
    raise ArgumentError, "<#{base.inspect}> must be a Hash" unless base.is_a? Hash
  end
end

usage:

external_data = JSON.decode( external_json )
flattened = Sparsify.sparse( external_data, :separator => '-' )

最初创建它是因为我们正在 Mongo 中存储一组内容,这允许我们在更新时使用稀疏键(点分隔)来更新嵌套哈希的某些内容,而不会覆盖不相关的键。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ruby:将嵌套 Ruby 哈希转换为非嵌套哈希 的相关文章

随机推荐