I am using HTTPparty gem to send request in my rails application. Here is an example:
order = HTTParty.get("https://sandbox.moip.com.br/v2/payments/#{o.payment_id}",
headers: {"Authorization" => "Basic #{encode_auth_token}"})
order_status = JSON.parse(order.body)
The variable order receives a json as response. I've managed to retrieve the information that I need, but i wanted to use symbols, instead of string to access the json data.
Is there any way to access my json data using symbols? For example:
order_status[:link]
Spoiler alert: best option is #3
Option 1: you can call .with_indifferent_access
on the Hash to be able to access the values by using either 'link'
or :link
:
{'a' => 1}[:a]
# => nil
{'a' => 1}.with_indifferent_access[:a]
# => 1
{'a' => 1}.with_indifferent_access['a']
# => 1
Option 2: call .symbolize_keys
(or .deep_symbolize_keys
if you want to symbolize the nested keys too) on the hash to convert all keys to symbols:
hash = { 'name' => 'Rob', 'address' => { 'postal_code' => '92210' } }
hash.symbolize_keys
# => {:name=>"Rob", :address=>{'postal_code'=>'92210'}}
hash.deep_symbolize_keys
# => {:name=>"Rob", :address=>{:postal_code=>'92210'}}
Option 3: parse the JSON with the symbolize_names
option set to true
JSON.parse(string, symbolize_names: true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With