我通过客户端ruby脚本对Ruby on Rails服务器进行JSON调用,该脚本返回以下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"
}
]
}
现在,我想从响应中提取某些值,以确定在客户端可以/不能做什么:
scan.rb
if get_functions('111aaa', 'can_scan')
result = %x( ping 10.10.10.1 )
else
result = "Not allowed to perform action!"
end
我仍然坚持如何从 get_data.rb 中的JSON中提取can_scan
的值,以便我的get_functions
方法能够运行if
声明正确。
答案 0 :(得分:2)
您的get_functions
正在返回nil
,因为最后一行是I / O操作(puts
)。将您的功能更改为:
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
访问哈希:
result = get_functions(serial_number, function)
result["device_functions"].first["can_scan"]