what is the best way to convert a json formatted key value pair to ruby hash with symbol as key?

Viewed 75848

I am wondering what is the best way to convert a json formatted key value pair to ruby hash with symbol as key: example:

{ 'user': { 'name': 'foo', 'age': 40, 'location': { 'city' : 'bar', 'state': 'ca' } } }
==> 
{ :user=>{ :name => 'foo', :age =>'40', :location=>{ :city => 'bar', :state=>'ca' } } }

Is there a helper method can do this?

8 Answers

The most convenient way is by using the nice_hash gem: https://github.com/MarioRuiz/nice_hash

require 'nice_hash'
my_str = "{ 'user': { 'name': 'foo', 'age': 40, 'location': { 'city' : 'bar', 'state': 'ca' } } }"

# on my_hash will have the json as a hash
my_hash = my_str.json

# or you can filter and get what you want
vals = my_str.json(:age, :city)

# even you can access the keys like this:
puts my_hash._user._location._city
puts my_hash.user.location.city
puts my_hash[:user][:location][:city]

If you think you might need both string and symbol keys:

JSON.parse(json_string).with_indifferent_access
Related