【问题标题】:rendering JSON based API response rails呈现基于 JSON 的 API 响应轨道
【发布时间】:2012-10-09 14:01:13
【问题描述】:

我正在努力呈现基于 JSON 的 API 的结果,并且正在努力解决如何正确地遍历结果。我的 API 调用的要点:

@invoice = ActiveSupport::JSON.decode(api_response.to_json)

得到的哈希数组如下:

{
"amount_due"=>4900, "attempt_count"=>0, "attempted"=>true, "closed"=>true, 
"currency"=>"usd", "date"=>1350514040, "discount"=>nil, "ending_balance"=>0, "livemode"=>false, 
"next_payment_attempt"=>nil, "object"=>"invoice", "paid"=>true, "period_end"=>1350514040, "period_start"=>1350514040, "starting_balance"=>0, 
"subtotal"=>4900, "total"=>4900, 
"lines"=>{
    "invoiceitems"=>[], 
    "prorations"=>[], 
    "subscriptions"=>[
        {"quantity"=>1, 
            "period"=>{"end"=>1353192440, "start"=>1350514040}, 
            "plan"=>{"id"=>"2", "interval"=>"month", "trial_period_days"=>nil, "currency"=>"usd", "amount"=>4900, "name"=>"Basic"}, 
            "amount"=>4900}
    ]
}}

我正在尝试循环显示所有“行”以进行渲染和开票。每个“行”可以有 0 个或多个“invoiceitems”、“prorations”和“subscriptions”。

我已经做到了这一点,但不知道如何处理任何嵌套。

<% @invoice["lines"].each_with_index do |line, index| %>

# not sure what the syntax is here ?

<% end %>

我目前正在视图中工作,但一旦我对其进行排序,我会将其中的大部分内容移至帮助程序。

谢谢!

【问题讨论】:

    标签: ruby-on-rails json parsing hash nested-loops


    【解决方案1】:

    根据您附加的示例 Hash,我怀疑您遇到了困难,因为您尝试枚举 @invoice["lines"] 中的对象,例如你会是一个数组。这样做的问题是对象是一个 Hash,因此枚举的处理方式略有不同。

    由于总是返回键 invoiceitemssubscriptionsprorations,并且还基于这些类别中的每一个可能看起来在生成的发票上有所不同,因为它们将具有不同的属性,您应该只对哈希中的 3 个值有 3 个单独的循环。我在下面编写了一个如何工作的示例:

    <% @invoice["lines"]["invoiceitems"].each_with_index do |item, index| %>
      # display logic of an invoice item
    <% end %>
    
    <% @invoice["lines"]["prorations"].each_with_index do |proration, index| %>
      # display logic of a proration
    <% end %>
    
    <table>
      <tr>
        <th>#</th>
        <th>Quantity</th>
        <th>Start Period</th>
        <th>Amount</th>
      </tr>
      <% @invoice["lines"]["subscriptions"].each_with_index do |subscription, index| %>
      <tr>
        # display logic of a subscription
        <td><%= index %></td>
        <td><%= subscription["quantity"] %></td>
        <td>
          <%= DateTime.strptime("#{subscription["period"]["start"]}",'%s').strftime("%m/%d/%Y") %>
        </td>
      </tr>
      <% end %>
    </table>
    

    虽然我没有完成订阅中的所有字段,但这应该足以作为继续进行的示例。

    【讨论】:

    • 顺便说一句 - 我注意到你使用了 DateTime.striptime。我一直在使用 Time.at(subscription["period"]["start"]).strftime('%m/%d/%Y') - 一个比另一个好?
    • 我不知道有什么区别,只是做同一件事的两种方式:)
    • 好的 - 再次感谢您提供如此完整的答案。我真的是用头撞那里的桌子!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 2021-05-11
    • 2018-09-01
    • 2016-11-16
    • 1970-01-01
    • 2015-08-24
    相关资源
    最近更新 更多