XYZ
XYZ

Reputation: 27397

How to convert nested string hash to symbol hash using Ruby?

The server is using JSON API which returns a nested data structure. I have tried to parse it using JSON.parse but it is converted the json string to string hash by default.

Sample Data

{
  "data"=>
  {
    "id"=>"1",
    "type"=>"users",
    "attributes"=>
    {
      "email"=>"[email protected]",
      "name"=>"Tanner Kreiger"
    }
  }
}

I have tried code below but it only convert one level deep (not children hash)

  def json_body
    str_hash = JSON.parse(response.body)
    str_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
  end

I have also tried symbolize_keys from Rails which only convert the first level as well (see :data and the rest is the same),

{:data=>{"id"=>"1", "type"=>"users", "attributes"=>{"email"=>"[email protected]", "name"=>"Cleo Braun"}}}

What is the best approach to recursively convert the nested string hash into symbol hash?

Desired Result

All the value can be access using symbol, like json_response[:data][:attributes].

Upvotes: 3

Views: 2203

Answers (1)

Coolness
Coolness

Reputation: 1992

Just use

JSON.parse(result, symbolize_keys: true)

More info http://apidock.com/ruby/JSON/parse

or on the hash itself

hash = { 'name' => 'Rob', 'age' => '28' }

hash.symbolize_keys
# => {:name=>"Rob", :age=>"28"}

http://apidock.com/rails/Hash/symbolize_keys

These don't seem to do it recursively though.

There's also deep_symbolize_keys! in Rails

http://api.rubyonrails.org/classes/Hash.html#method-i-deep_symbolize_keys

Upvotes: 3

Related Questions