如何从这个散列中获得last_4键的值?
我有一个来自Square事务的响应nonce。我通过Ajax将响应传递给Ruby,在那里它以参数字符串的形式出现。Iv'e尝试将字符串转换为散列。我也尝试过JSON.parse。
这是来自Square沙箱事务的实际响应nonce。我已经截断了一些ID,并替换了其他ID。此外,我还添加了回车符,以使其更具可读性:
{:transaction=>{
:id=>"smqfzS00qbp1lOy...",
:location_id=>"CBASE...",
:created_at=>"2019-02-19T19:45:18Z",
:tenders=>[{
:id=>"34670bfa-9d09-406a-910c-9c3e8ab82321",
:location_id=>"CBASE...",
:transaction_id=>"smqfzS00qbp1lOy...",
:created_at=>"2019-02-19T19:45:18Z",
:note=>"Online Transaction",
:amount_money=>{
:amount=>65000,
:currency=>"USD"
},
:type=>"CARD",
:card_details=>{
:status=>"CAPTURED",
:card=>{
:card_brand=>"VISA",
:last_4=>"9999",
:fingerprint=>"22737c9b012a..."
},
:entry_method=>"KEYED"
}
}],
:product=>"EXTERNAL_API"
}
}
我将其作为ajax调用中的字符串,并将其转换为散列或进行解析:
sqresp = Hash.new(square_resp) # this works
sqresp = JSON.parse(square_resp) # this fails
我试着只取出id,这是第一个嵌套的键:
sqresp[:transaction] # this works but I get the whole string
但如果我再深入一步,它就失败了:
sqresp[:transaction][:id] # this fails
sqresp[:transaction[:id]] # kinda makes sense but fails
sqresp[:transaction][:tenders][:amount_money][:card_details][:card][:last_4] # of course this fails too,it's just a deeper scrape.
如果有一个Ruby方法来分解所有的Square键/值,那就太好了,但是通过一个如何提取last_4的例子,我可以做剩下的事情。
谢谢。
发布于 2019-03-26 20:33:36
凯里,成功了!
sqresp = instance_eval(square_resp)
sqresp[:transaction][:tenders].first[:card_details][:card][:last_4]
谢谢!没有为你的评论投票的选项。
https://stackoverflow.com/questions/55365027
复制相似问题