Question

How do I extract the values for title, URL and image (commented section below) from a hashed Amazon Products API response?

I'm using Vacuum to interact with Amazon. Apparently I can't use map as Vacuum::Response only accepts to_h?

Currently getting:

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

Was it helpful?

Solution

'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']}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top