2015-05-14 54 views
0

我使用紅寶石和sinatra。在Stripe API調用之後,我想從JSON返回中訪問一個元素,並將其放入我的數據庫中。如何從條紋api調用中獲取JSON retunr的元素?

的Ruby代碼是:

需要'Sinatra的

require 'stripe' 
require 'pg' 
require 'sequel' 

get '/save_customer' do 
customer = Stripe::Customer.retrieve("cus_6EfJSbJ8gCTxxx") 
puts customer 
last4 = customer["sources"]["data"]["last4"] 
DB[:stripe_customers].insert(:user_id=>user_id, :email=>email, :stripe_customer_id=>customer_id, :stripe_customer_card=> last4) 
end 

的JSON(從API文檔,不是我回來取)如下:

{ 
    "object": "customer", 
    "created": 1431570089, 
    "id": "cus_6EfJSbJ8gCTxxx", 
    "livemode": false, 
    "description": "Example customer", 
    "email": null, 
    "delinquent": false, 
    "metadata": { 
    }, 
    "subscriptions": { 
    "object": "list", 
    "total_count": 0, 
    "has_more": false, 
    "url": "/v1/customers/cus_6EfJSbJ8gCTMrd/subscriptions", 
    "data": [ 

    ] 
    }, 
    "discount": null, 
    "account_balance": 0, 
    "currency": "usd", 
    "sources": { 
    "object": "list", 
    "total_count": 1, 
    "has_more": false, 
    "url": "/v1/customers/cus_6EfJSbJ8gCTMrd/sources", 
    "data": [ 
     { 
     "id": "card_162ByRBVd5ndD62KfaONcG4G", 
     "object": "card", 
     "last4": "4242", 
     "brand": "Visa", 
     "funding": "credit", 
     "exp_month": 12, 
     "exp_year": 2018, 
     "country": "US", 
     "name": null, 
     "address_line1": null, 
     "address_line2": null, 
     "address_city": null, 
     "address_state": null, 
     "address_zip": "123456", 
     "address_country": null, 
     "cvc_check": "pass", 
     "address_line1_check": null, 
     "address_zip_check": "pass", 
     "dynamic_last4": null, 
     "metadata": { 
     }, 
     "customer": "cus_6EfJSbJ8gCTxxx" 
     } 

我有嘗試過:

last4 = customer[:data][:sources][:last4] 

""

Th錯誤信息有所不同,目前有TypeError - no implicit conversion of String into Integer。我說這是因爲我沒有正確提取我需要的元素,或者這可能意味着api調用不起作用,但我認爲它確實如此。

任何人都可以幫忙嗎?

一如既往的感謝。

回答

0

試試這個:

last4 = customer["sources"]["data"][0]["last4"] 
+0

謝謝你,它的工作原理。請你能告訴我爲什麼需要[0]?我不明白! – user1903663

+0

'customer [「sources」] [「data」]'是一個數組,因此您需要指定一個索引。 –

+0

謝謝,我學到了非常有用的東西。 – user1903663