16

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

Simone
  • 20,302
  • 14
  • 79
  • 103
Leonardo
  • 2,273
  • 6
  • 29
  • 32

3 Answers3

24

I would suggest using open-uri:

require 'json'
require 'open-uri'
result = JSON.parse open('http://example.com/data.json').read
KL-7
  • 46,000
  • 9
  • 87
  • 74
  • I have found that `OpenURI::HTTPError` gives much less information than the errors returned by `Net::HTTP`. It's been a while since I stopped using `OpenURI`, but if I recall correctly, it didn't even tell me the status code, so 404 was treated the same as 500. – maurice Apr 22 '16 at 19:31
  • @maurice, it does in fact tell you the HTTP status code, here's an example of a 404 wrapped by `OpenURI::HTTPError` - `404 Not Found` – Dmitrii Kharlamov Jul 16 '21 at 15:10
6
require 'net/http'
uri = URI('http://my.json.emitter/some/action')
json = Net::HTTP.get(uri)

json will contain the JSON string you fetched from uri.

Then read this StackOverflow post.

Community
  • 1
  • 1
dave
  • 2,199
  • 1
  • 16
  • 34
1
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
  1. I specifically include open-uri, so that open is called from that module instead of attempting to call a private open from the Kernel module.
  2. I intentionally parse the URL to avoid a security risk - https://rubydoc.info/gems/rubocop/RuboCop/Cop/Security/Open
  3. Unlike some commenters pointed out above, OpenURI does indicate the HTTP status code of an error.