【问题标题】:Pull values from Shopify response array从 Shopify 响应数组中提取值
【发布时间】:2016-10-07 22:55:35
【问题描述】:

这一定是有史以来最愚蠢的问题,但我如何从这个 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 但 orders[0].to_json['email'] 返回电子邮件。我已经尝试过诸如 order[0][1] 和 orders[0]['id'] 之类的东西。但我什么都做不了。我错过了什么?

【问题讨论】:

  • 在控制台或调试器中,输入orders.first,看看你会得到什么。
  • 也试过了,它返回 #<:order:0x007fd66abf38d8>
  • 试试orders.first.email。 API 应将属性直接映射到方法。所以orders.first.email/order_number/billing_address 等可能有效。

标签: ruby-on-rails ruby shopify


【解决方案1】:

您应该这样做(取决于 Shopify 是否在 attributes 实例变量上定义了 attr_reader

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

【讨论】:

  • 我认为 API 将属性直接映射到方法。所以orders.first.email 应该这样做。虽然不是 100% 确定这一点,但如果不这样做似乎很愚蠢。
  • @Casper 确实很有意义(我也不熟悉 shopify 的 API)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 2013-08-15
  • 2021-12-12
  • 1970-01-01
  • 2020-08-18
相关资源
最近更新 更多