0

これは私の YELP クライアントが署名を使用していますが、応答を取得すると、ルビー ハッシュに変換して応答要素を検査することができません。

require 'rubygems'
require 'json'
require 'net/http'


client = Signet::OAuth1::Client.new(
  :client_credential_key =>
    'xxxxxxxxxxxxxxxxxxx',
  :client_credential_secret =>
    'xxxxxxxxxxxxxxxxxxx',
  :token_credential_key =>
    'xxxxxxxxxxxxxxxxxxx',
  :token_credential_secret => 
    'xxxxxxxxxxxxxxxxxxx'
)
response = client.fetch_protected_resource(
  :uri => 'http://api.yelp.com/v2/search?term=food&location=san+francisco'
)
# The Rack response format is used here
status, headers, body = response
puts body["businesses"]

エラー: `[]': 文字列を整数に変換できません (TypeError)

本文は素敵な JSON 形式で正常に出力されますが、body["businesses"] を実行できます。たとえば、JSON.parse(body).inspect も機能しません。

ところで、ボディ出力自体は JSON 形式として表示されますが、JSON.parse(body) はハッシュを生成しません

puts body

{"region":{"span":{"latitude_delta":0.0,"longitude_delta":0.0},"center":{"latitude":37.660418999999997,"longitude":-121.876508}},"total":853,"businesses":[{"rating":4.0,"mobile_url":"http://m.yelp.com/biz/TT1t4oHeZmqkoiuwgCN4bQ","rating_img_url":"http://media2.ak.yelpcdn.com/static/201012164084228337/img/ico/stars/stars_4.png","review_count":150,"name":"India Garden","rating_img_url_small":"http://media2.ak.yelpcdn.com/static/20101216418129184/img/ico/stars/stars_small_4.png","url":"http://www.yelp.com/biz/india-garden-pleasanton-2","phone":"9254854800","snippet_text":"We went to this place without seeing any reviews while we returning to San Jose from Cache Creek in Brooks. This place looks like a house which was...","image_url":"http://s3-media4.ak.yelpcdn.com/bphoto/8iFj1S9YaU5IdUazwZOG8A/ms.jpg","snippet_image_url":"http://s3-media3.ak.yelpcdn.com/photo/d2TovvsTn2eUw4xqTB4jyw/ms.jpg","display_phone":"+1-925-485-4800","rating_img_url_large":"http://media4.ak.yelpcdn.com/static/20101216169592178/img/ico/stars/stars_large_4.png","id":"india-garden-pleasanton-2","categories":[["Indian","indpak"],["Pakistani","pakistani"]],"location":{"cross_streets":"Main St & Neal St","city":"Pleasanton","display_address":["210 Rose Ave","(b/t Main St & Neal St)","Pleasanton, CA 94566"],"geo_accuracy":8,"postal_code":"94566","country_code":"US","address":["210 Rose Ave"],"coordinate":{"latitude":37.660418999999997,"longitude":-121.876508},"state_code":"CA"}}]}
4

2 に答える 2

1

実際には、応答には 3 つではなく 4 つの部分が含まれているため、この時点でボディは配列であると確信しているため、最後の 2 つの部分 (配列) がボディオブジェクトに入れられます。

また、配列は私が知っている唯一のコアオブジェクトであり、[] パラメーターが整数ではないことについて不平を言っています。文字列の場合は、regex/contain の一致を試みます。

要約すると、body は、文字列を含む値を 1 つだけ持つ配列です。したがって、(JSON から) ハッシュを取得するには、real_body = JSON.parse body[0]. 次に、ハッシュを取得し real_body["businesses"]てビジネスを配置する必要があります(出力はかなり長いので、ここには投稿しません)

于 2011-10-21T11:55:51.887 に答える
0

body は、この時点では文字列であり、ハッシュではありません。[] 演算子は、文字列 [] 演算子が整数のみを受け取るため、不平を言っているため、文字列を整数に変換しようとして失敗しています。

編集:body.classを印刷するだけでこれをテストできます

于 2011-10-21T07:36:53.830 に答える