Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use symbols to access a JSON response with HTTParty?

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]
like image 896
Gabriel Mesquita Avatar asked Jan 30 '23 18:01

Gabriel Mesquita


1 Answers

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)
like image 102
MrYoshiji Avatar answered Feb 03 '23 07:02

MrYoshiji