在Ruby中访问JSON对象

use*_*137 3 ruby json ruby-on-rails

我有一个看起来像这样的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"
              }
            ]
          }
        ]
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'

json = File.read('input.json')
Run Code Online (Sandbox Code Playgroud)

有没有人知道ruby和json有什么好资源给新来的人?

max*_*max 6

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?
Run Code Online (Sandbox Code Playgroud)