繁体   English   中英

Ruby on Rails:遍历Json结构

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM