Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

ruby - Rails: How to extract values from hash? (Amazon API / Vacuum)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

'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']}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...