LoginSignup
283
282

More than 5 years have passed since last update.

RubyでJSON形式の結果が返ってくるURLをParseする

Last updated at Posted at 2013-02-18

HTTPリクエストでJSONが返ってくるAPIを処理するとかよくあるケースだけど、意外と書き方忘れるのでメモ

require 'net/http'
require 'uri'
require 'json'

uri = URI.parse('http://www.example.com/sample.json')
json = Net::HTTP.get(uri)
result = JSON.parse(json)
puts result

RedirectとかTimeoutとかエラー処理とかちゃんとやりたい時用

require 'net/http'
require 'uri'
require 'json'

def get_json(location, limit = 10)
  raise ArgumentError, 'too many HTTP redirects' if limit == 0
  uri = URI.parse(location)
  begin
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
      http.open_timeout = 5
      http.read_timeout = 10
      http.get(uri.request_uri)
    end
    case response
    when Net::HTTPSuccess
      json = response.body
      JSON.parse(json)
    when Net::HTTPRedirection
      location = response['location']
      warn "redirected to #{location}"
      get_json(location, limit - 1)
    else
      puts [uri.to_s, response.value].join(" : ")
      # handle error
    end
  rescue => e
    puts [uri.to_s, e.class, e].join(" : ")
    # handle error
  end
end

puts get_json('http://www.example.com/sample.json')

公式ドキュメント

日本語版ドキュメント

283
282
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
283
282