简体   繁体   中英

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

I used above method that returns the json given below:-

{: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"]}

Now in my view i want to show structure from above output so the view should look like

public
 422.html
 applications
  1
   1
    1
    2
  2
.....
.....
.....

An So On

I have a variable that keeps this json

@structure = ApplicationVersion.directory_hash("public")

So what code i will need to write to read the above json so that tree could be constructed?

Try:

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] != ":"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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