Reputation: 2363
here my file: http://example.com/test.txt
i have to read content of http://example.com/test.txt (a JSON string) and parse it in Ruby
Upvotes: 17
Views: 21635
Reputation: 309
require 'json'
require 'open-uri'
uri = URI.parse 'http://example.com/test.txt'
json =
begin
json_file = uri.open.read
rescue OpenURI::HTTPError => e
puts "Encountered error pulling the file: #{e}"
else
JSON.parse json_file
end
open-uri
, so that open
is called from that module instead of attempting to call a private open
from the Kernel
module.OpenURI
does indicate the HTTP status code of an error.Upvotes: 1