JSON keys as symbols instead of strings in Ruby

Here’s a quickie that saved me from having to write a recursive symbolize_keys method.  I was dealing with stringified JSON in the params of one of my rails controllers.  I wanted to do the usual call to params[:foo], but when I did JSON.parse  on the string, the keys were strings instead of symbols, so I would need to do params[‘foo’] instead.  Luckily, as of Ruby 1.9, it’s possible to pass in symbolize_names: true as an option.

s = '{"hello": "kitty", "mickey": "mouse"}'
=> "{\"hello\": \"kitty\", \"mickey\": \"mouse\"}"

JSON.parse(s)
=> {"hello"=>"kitty", "mickey"=>"mouse"}

JSON.parse(s, symbolize_names: true)
=> {:hello=>"kitty", :mickey=>"mouse"}

 

Related Posts with Thumbnails

Leave a Reply

Your email address will not be published. Required fields are marked *