我正在使用vaccum从亚马逊产品广告API获取产品详细信息。请求= Vacuum.new
req.configure(key: configatron.api.amazon.productAPI.key,
secret: configatron.api.amazon.productAPI.secret,
tag: 'biz-val')
regex = Regexp.new "http://([^/]+)/([\\w-]+/)?(dp|gp/product|exec/obidos/asin)/(\\w+/)?(\\w{10})"
productID=regex.match(@url).captures[4];
host=regex.match(@url).captures[0];
utype=regex.match(@url).captures[2];
@url="http://#{host}/#{utype}/#{productID}"
params = { 'Operation' => 'ItemLookup',
'ItemId' => productID,
'ResponseGroup'=>'Large'
}
res = req.get(:query => params)
hsh=Hash.from_xml(res.body)
@details=hsh
item=hsh[:ItemLookupResponse][:Items][:Item]#Throws an Undefined method [] for nilClass您可以忽略正则表达式解析。我已经检查了从res.body生成的fine.The散列是一个有效的散列,它在json呈现的(@details)中显示得很好,但当我试图在代码中访问它时,它抛出了一个nilClass的东西。我认为这可能是因为hsh[:ItemLookupResponse]返回的不是散列。不过,我不确定它返回的是什么。如何访问:项目?
发布于 2013-09-10 12:06:05
如果它显示您正试图在NilClass上调用[],那么很可能是这样的。在这一特定行上,您可以对这三个行调用[]
hsh
hsh[:ItemLookupResponse]
hsh[:ItemLookupResponse][:Items]因此,其中一个很有可能是nil。您可能希望使用调试器/repl并将断点放在错误行之前,然后检查hsh。我使用pry,您可以先使用require 'pry',然后将binding.pry放在您想要的断点位置。
https://stackoverflow.com/questions/18710176
复制相似问题