1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

sinatra で json を読み込んだ場合のエラー回避

Posted at

はじめに

sinatrajsonを読み込んだ際、undefined method bytesizeが発生しました。

sinatra undefined method bytesize で検索すると、sinatra と json の相性が悪いらしいのですが、Hash -> json の話が多いようです。

この記事は、json -> Hash 時のエラー回避策です。

状況

error.rb
require 'net/http'
require 'uri'
require 'json'

def read_uri(url)
  uri = URI.parse(url)
  res = Net::HTTP.get(uri)
    
  json_data = JSON.parse(res)

最後の行でundefined method bytesizeが発生。

対策

success.rb
def read_uri(url)
  uri = URI.parse(url)
  res = Net::HTTP.get(uri)
    
-  json_data = JSON.parse(res)
+  json_data = JSON.parse(res.chomp)

とりあえず、改行コードを削除するといい様です。

参照したサイト

1
0
4

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?