Accessing JSON Objects in Ruby

I have a json file that looks something like this:

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

      

How to print only domain and access only module.names in ruby ​​and print module.names to console:

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

json = File.read('input.json')

      

and does anyone know of good resources for rubies and json for someone new to it?

+3


source to share


3 answers


JSON.parse

takes a JSON string and returns a hash that can be manipulated just like any other hash .



#!/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?

      

+6


source


In Ruby, you must use square brackets to access hashes.

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

      



However, this is Ruby ... so you can also override the Hash class and access your hashes using simple dot notation. (simple solution: @papirtiger) For example: domain = json.Results.Paths.Domain

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

      

+3


source


You may try:

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

      

+1


source







All Articles