How to parse Square response nested key values in Ruby 2.2.10

情到浓时终转凉″ 提交于 2019-12-13 04:44:29

问题


How would you get the value of the last_4 key form this hash?

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.

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"
    }
}

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

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.

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.

Thanks.


回答1:


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.



来源:https://stackoverflow.com/questions/55365027/how-to-parse-square-response-nested-key-values-in-ruby-2-2-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!