Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JSON objects in Ruby [closed]

I have a json file that looks kind of 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 do I print only the domain and access only the module.names in ruby and print the module.names to the console:

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

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

and does any one know of any good resources for ruby and json for someone new to it?

like image 266
user3610137 Avatar asked Feb 13 '26 01:02

user3610137


1 Answers

JSON.parse takes a JSON string and return a hash which 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?
like image 94
max Avatar answered Feb 14 '26 15:02

max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!