Rails: get values of http response

2019-02-11 11:01发布

问题:

In rails I made a post to an api and got a response, but I don't know how to get through the information and find the value of the "code" variable.

$ response 
#<Net::HTTPOK 200 OK readbody=true>

$ puts response.body
{"success":true,"button":{"code":"dfhdsg7f23hjgfs7be7","type":"buy_now","style":"none","text":"Send to MeBrah","name":"MeBrah","description":"Coins you&#x27;re willing to give me.","custom":"6","callback_url":null,"success_url":null,"cancel_url":null,"info_url":null,"auto_redirect":false,"price":{"cents":40000000,"currency_iso":"BTC"},"variable_price":true,"choose_price":false,"include_address":false,"include_email":false}}

$ response.code
"200"  

I know the code variable is equal too "dfhdsg7f23hjgfs7be7" I'm just curious what command would return it's value.

回答1:

Parse the response content with JSON.parse:

require 'json'

...

data = JSON.parse(response.body)
data['button']['code'] # => "dfhdsg7f23hjgfs7be7"