【发布时间】:2012-08-21 23:52:35
【问题描述】:
现在,我有一个服务器调用回退了以下 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”和“wed-end”或类似的字段中。
有人对如何开始有任何提示吗?
【问题讨论】:
-
对您在这里使用“JSON”有点困惑。您显示的是 ruby 哈希,而不是 JSON 对象。您是否需要展平该哈希,然后转换回 JSON?或者,您是否只需要获取该红宝石哈希并将其展平?
-
是的,原来它实际上是一个红宝石对象。我如何将其展平?
-
有一个名为 flatten 的哈希方法,但我认为这不是您要寻找的。它将散列扁平化为数组。我很好奇你的用例是什么。恕我直言,保持嵌套通常更有意义。动态检索像
hash[var][var2]这样的值要比像hash[var + "-" +var2]这样动态地连接键要容易得多。它的可读性较差,并没有真正获得太多。
标签: ruby hash nested-attributes