在Ruby中访问JSON对象

我有一个看起来像这样的json文件:

{ "Results": [ { "Lookup": null, "Result": { "Paths": [ { "Domain": "VALUE1.LTD", "Url": "", "Text1": "", "Modules": [ { "Name": "VALUE", "Tag": "VALUE", "FirstDetected": "1111111111", "LastDetected": "11111111111" }, { "Name": "VALUE", "Tag": "VALUE", "FirstDetected": "111111111111", "LastDetected": "11111111111111" } ] } ] } } ] } 

如何仅打印域并仅访问ruby中的module.names并将module.names打印到控制台:

 #!/usr/bin/ruby require 'rubygems' require 'json' require 'pp' json = File.read('input.json') 

任何人都知道ruby和json有什么好资源可供新手使用吗?

JSON.parse接受一个JSON字符串并返回一个可以像任何其他哈希一样操作的哈希 。

 #!/usr/bin/ruby require 'rubygems' require 'json' require 'pp' # Symbolize keys makes the hash easier to work with data = JSON.parse(File.read('input.json'), symbolize_keys: true) # loop through :Results if there are any data[:Results].each do |r| # loop through [:Result][:paths] if there are any r[:Result][:paths].each do |path| # path refers the current item path[:Modules].each do |module| # module refers to the current item puts module[:name] end if path[:Modules].any? end if r[:Result][:paths].any? end if data[:Results].any? 

在Ruby中,您必须使用方括号来访问哈希。

 json =JSON.parse(File.read('input.json')) domains = [] json.Results.map{|result| result.Paths.map{|path| domains << path.Domain }} 

但它是Ruby ...所以你也可以覆盖Hash类并使用简单的点表示法访问你的Hashes。 (通过简单的解决方案:@papirtiger)例如:domain = json.Results.Paths.Domain

 require 'ostruct' JSON.parse(File.read('input.json'), object_class: OpenStruct) 

你可以试试:

 json_file = JSON.parse(File.read('input.json')) json_file[:Results].each {|y| y[:Result][:Paths].each do |a| puts "Domain names: #{a[:Domain]}" a[:Modules].each {|b| puts "Module names are: #{b[:Name]}" } end } #=> Domain names: VALUE1.LTD #=> Module names are: VALUE #=> Module names are: VALUE