[英]Ruby on Rails: Traverse Json Structure
def self.directory_hash(path, name=nil)
data = {:parent => (name || path)}
data[:children] = children = []
Dir.foreach(path) do |entry|
next if (entry == '..' || entry == '.')
full_path = File.join(path, entry)
if File.directory?(full_path)
children << directory_hash(full_path, entry)
else
children << entry
end
end
return data
end
我用上面的方法返回了下面給出的json:-
{:parent=>"public", :children=>["422.html", {:parent=>"applications", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>["configurations.xml"]}, {:parent=>"2", :children=>["configurations.xml"]}, "Projects.rar"]}, {:parent=>"2", :children=>[{:parent=>"9", :children=>["configurations.xml"]}, "rest.rar", {:parent=>"5", :children=>["configurations.xml"]}, {:parent=>"6", :children=>["configurations.xml"]}, {:parent=>"3", :children=>["configurations.xml"]}, {:parent=>"4", :children=>["configurations.xml"]}]}]}, {:parent=>"2", :children=>[{:parent=>"3", :children=>["Projects.rar"]}, {:parent=>"4", :children=>["rest.rar"]}]}]}, "500.html", "robots.txt", "favicon.ico", {:parent=>"data", :children=>[]}, "_index.html", "404.html"]}
現在在我看來,我想顯示輸出上方的結構,因此該視圖應該看起來像
public
422.html
applications
1
1
1
2
2
.....
.....
.....
一個如此
我有一個保留此json的變量
@structure = ApplicationVersion.directory_hash("public")
那么我將需要編寫什么代碼來讀取上面的json以便構建樹?
嘗試:
your_hash = {:parent=>"public", :children=>["422.html", {:parent=>"applications", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>["configurations.xml"]}, {:parent=>"2", :children=>["configurations.xml"]}, "Projects.rar"]}, {:parent=>"2", :children=>[{:parent=>"9", :children=>["configurations.xml"]}, "rest.rar", {:parent=>"5", :children=>["configurations.xml"]}, {:parent=>"6", :children=>["configurations.xml"]}, {:parent=>"3", :children=>["configurations.xml"]}, {:parent=>"4", :children=>["configurations.xml"]}]}]}, {:parent=>"2", :children=>[{:parent=>"3", :children=>["Projects.rar"]}, {:parent=>"4", :children=>["rest.rar"]}]}]}, "500.html", "robots.txt", "favicon.ico", {:parent=>"data", :children=>[]}, "_index.html", "404.html"]}
new_hash= your_hash.to_s.gsub(/(\[\"\S*\"\])/,'').gsub(/(\[|\]|\{|\})/,'').gsub('=>',',').gsub(',,',',')
new_hash.split(',').each {|i| puts i if i.strip[0] != ":"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.