Reputation: 2512
I am making a JSON call to a Ruby on Rails server via a client side ruby script, which returns the following JSON:
get_data.rb
require 'net/http'
require 'open-uri'
require 'json'
def get_functions(serial_number, function)
request_uri = "http://localhost:3000/devices/#{serial_number}"
buffer = open(request_uri).read
result = JSON.parse(buffer)
puts result
end
{ "serial_number" => "111aaa",
"device_functions" => [
{ "can_scan" => true,
"can_halt" => true
}
],
"host_options" => [
{ "exclude_ip" => "10.10.10.100-110",
"scan_ip" => "10.10.10.1"
}
]
}
Now, I'm wanting to just extract certain values from the response to determine what can/cannot be done on the client side:
scan.rb
if get_functions('111aaa', 'can_scan')
result = %x( ping 10.10.10.1 )
else
result = "Not allowed to perform action!"
end
I'm stuck with how I can extract the value of can_scan
from my JSON in get_data.rb for my get_functions
method to be able to run its if
statement correctly.
Upvotes: 0
Views: 2300
Reputation: 738
Your get_functions
is returning nil
as the last line is an I/O operation (puts
). Change your function to:
def get_functions(serial_number, function)
request_uri = "http://localhost:3000/devices/#{serial_number}"
buffer = open(request_uri).read
result = JSON.parse(buffer)
puts result
result
end
And access the Hash:
result = get_functions(serial_number, function)
result["device_functions"].first["can_scan"]
Upvotes: 4