本文介绍了扶手:如何从哈希提取值? (亚马逊API /真空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何从一个散列亚马逊产品API响应中提取的标题,URL和图像(下文注释部分)的值?
How do I extract the values for title, URL and image (commented section below) from a hashed Amazon Products API response?
我使用真空与亚马逊的互动。显然,我不能使用地图
为真空::响应
只接受 to_h
?
I'm using Vacuum to interact with Amazon. Apparently I can't use map
as Vacuum::Response
only accepts to_h
?
目前越来越
can't convert String into Integer
main_controller.rb
class MainController < ApplicationController
def index
request = Vacuum.new('GB')
request.configure(
aws_access_key_id: 'ABCDEFGHIJKLMNOPQRST',
aws_secret_access_key: '<long messy key>',
associate_tag: 'lipsum-20'
)
params = {
'SearchIndex' => 'Books',
'Keywords'=> 'Ruby on Rails',
'ResponseGroup' => "ItemAttributes,Images"
}
raw_products = request.item_search(query: params)
hashed_products = raw_products.to_h
# NOT WORKING
puts hashed_products['ItemSearchResponse']['Items']['Item']['ItemAttributes']['Title']
puts hashed_products['ItemSearchResponse']['Items']['Item']['DetailPageURL']
puts hashed_products['ItemSearchResponse']['Items']['Item']['LargeImage']['URL']
# NOT WORKING
# @products = hashed_products do |product|
# product.name hashed_products['ItemSearchResponse']['Items']['Item']['ItemAttributes']['Title']
# product.url hashed_products['ItemSearchResponse']['Items']['Item']['DetailPageURL']
# product.image hashed_products['ItemSearchResponse']['Items']['Item']['LargeImage']['URL']
# end
# REDUNDANT EXAMPLE FROM OTHER PROJECT
# @products = raw_products.map do |product|
# product = OpenStruct.new(product)
# image = product.images.find { |i| i["LargeImage"] == 'URL' }
# product.image = OpenStruct.new(image)
# product
# end
end
end
index.html.erb
<h1>Products from Amazon Product Advertising API</h1>
<% if @products.any? %>
<% @products.each do |product| %>
<div class="product">
<%= link_to image_tag(product.image.url), product.url %>
<%= link_to product.name, product.url %>
</div>
<% end %>
<% end %>
亚马逊响应的完整例子可以在这里找到:
Full example of Amazon response can be found here:
https://gist.github.com/frankie-loves-jesus/89d24dd88579c7f912f3
推荐答案
项目是一个数组,所以你需要遍历它来收集标题和其他属性。示例
'Item' is an array, so you would need to loop through it to collect the 'Title' and other attributes. Example
puts hashed_products['ItemSearchResponse']['Items']['Item'].collect{|i| i['ItemAttributes']['Title']}
这篇关于扶手:如何从哈希提取值? (亚马逊API /真空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!