如何在Ruby 2.2.10中解析Square响应嵌套键值 [英] How to parse Square response nested key values in Ruby 2.2.10
问题描述
如何从此哈希中获取last_4键的值?
How would you get the value of the last_4 key form this hash?
我有一个Square交易的响应随机数.我将响应通过Ajax传递给Ruby,该响应以参数字符串的形式出现.我尝试将字符串转换为哈希.我也尝试过JSON.parse.
I have a response nonce from a Square transaction. I pass the response through Ajax to Ruby where it comes out as a parameter string. Iv'e tried converting the string to a hash. I've also tried JSON.parse.
这是来自Square沙盒事务的实际响应随机数.我已经截断了一些ID,并替换了其他ID.另外,我还输入了回车符以使其更易于阅读:
This is an actual response nonce from a Square sandbox transaction. I've truncated some of the IDs and replaced others. Also i put in carriage returns to make it more human readable:
{: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调用的字符串,并将其转换为哈希或对其进行解析:
I have it as a string from an ajax call and convert it to a hash or parse it:
sqresp = Hash.new(square_resp) # this works
sqresp = JSON.parse(square_resp) # this fails
我尝试仅提取id(这是第一个嵌套键):
I've tried pulling out just the id, which is the first nested key:
sqresp[:transaction] # this works but I get the whole string
但是,如果我再深入一点,它就会失败:
But if I go any deeper it fails:
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.
拥有一个用于分解所有Square键/值的Ruby方法会很棒,但是通过一个如何提取last_4的示例,我可以完成其余工作.
It would be great to have a Ruby method for breaking out all the Square key/values but with an example of how to pull out last_4, I can do the rest.
谢谢.
推荐答案
Cary,效果很好!
Cary, that worked!
sqresp = instance_eval(square_resp)
sqresp[:transaction][:tenders].first[:card_details][:card][:last_4]
谢谢! 无法对您的评论进行投票.
Thanks! There's no option to vote for your comment.
这篇关于如何在Ruby 2.2.10中解析Square响应嵌套键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!