0

这是我使用 signet 的 YELP 客户端,但是一旦我得到响应,我就无法转换为 ruby​​ 哈希来检查响应元素。

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

实际上我很确定,此时该主体是一个数组,因为响应包含四个部分而不是三个部分,所以最后两个部分(一个数组)被放入主体对象中。

Array 也是我知道的唯一核心对象,它抱怨 [] 参数不是整数。如果它是一个字符串,它会尝试一个正则表达式/包含匹配。

综上所述,body 是一个数组,其中只有一个 Value 包含一个 String。因此,要获取您的哈希(来自 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 回答