这一直是最愚蠢的问题,但我如何从这个Shopify API响应中提取值?
orders = [#<ShopifyAPI::Order:0x007fb987a4f900 @attributes={"id"=>4141918472, "email"=>"fake@fakemail.com", "created_at"=>"2016-09-28T14:12:49-05:00", "total_price"=>"109.99", "order_number"=>1001, "billing_address"=>#<ShopifyAPI::BillingAddress:0x007fb987a4e410 @attributes={"first_name"=>"John", "address1"=>"111 Fake St", "phone"=>nil, "city"=>"Los Angeles", "zip"=>"90210", "province"=>"California", "country"=>"United States", "last_name"=>"Doe", "address2"=>"", "company"=>nil, "latitude"=>34.0670499, "longitude"=>-118.2714165, "name"=>"John Doe", "country_code"=>"US", "province_code"=>"CA"}, @prefix_options={}, @persisted=true>}, @prefix_options={}, @persisted=true>, #<ShopifyAPI::Order:0x007fb987a46b98 @attributes={"id"=>4141925128, "email"=>"aljdsfjalidsfnadf123132@yahoo.com", "created_at"=>"2016-09-28T14:14:25-05:00", "total_price"=>"309.97", "order_number"=>1002, "billing_address"=>#<ShopifyAPI::BillingAddress:0x007fb987a456f8 @attributes={"first_name"=>"afd", "address1"=>"744 Fake", "phone"=>nil, "city"=>"Chicago", "zip"=>"60021", "province"=>"Illinois", "country"=>"United States", "last_name"=>"adsfasd", "address2"=>"", "company"=>nil, "latitude"=>42.1976923, "longitude"=>-88.2120315, "name"=>"afd adsfasd", "country_code"=>"US", "province_code"=>"IL"}, @prefix_options={}, @persisted=true>}, @prefix_options={}, @persisted=true>]
我使用了orders.class,它说它是一个数组。这是一个散列数组吗?我可以使用.to_json但订单[0] .to_json [&#39; email&#39;]会返回电子邮件。我尝试过订单[0] [1]和订单[0] [&#39; id&#39;]等内容。但我无法得到任何工作。我错过了什么?
答案 0 :(得分:3)
您应该这样做(取决于Shopify是否在attr_reader
实例变量上定义attributes
)
orders.first.attributes
或
order.first.instance_variable_get(:@attributes)
获取所有订单的数据:
orders.map(&:attributes)
# or, if above is not working, but it should
orders.map {|order| order.instance_variable_get(:@attributes) }
根据@ Casper的评论,如果API为读者提供属性,那么能够执行以下操作是合乎逻辑的:
orders.first.email # or any other attribute