Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash keys as symbol not working

Tags:

ruby

I'm confused as to why the symbol version of the key does not work in the following example. As indicated, I am using Ruby 1.9.3. This is part of a much larger app, but have been able to narrow it down to this problem.

Thank you in advance!

1.9.3-p194 :002 > json_sample = "{\"this\":\"notworking\"}"
=> "{\"this\":\"notworking\"}"
1.9.3-p194 :003 > test_hash = JSON.parse json_sample
=> {"this"=>"notworking"}
1.9.3-p194 :004 > test_hash["this"]
=> "notworking"
1.9.3-p194 :005 > test_hash[:this]
=> nil

like image 515
Jeff Erickson Avatar asked Nov 30 '22 22:11

Jeff Erickson


1 Answers

JSON, being a subset of JavaScript, does not have a notion of symbols. All keys are strings--thus, when you parse JSON with Ruby, the hash is created with strings as the keys.

If you're used to working with Ruby on Rails, you may be used to working with HashWithIndifferentAccesses, which allow you to use either strings or symbols for your keys.


[Update] As mentioned by akuhn in the comments, you can force the JSON module to symbolize all the keys by passing symbolize_names: true to the options for JSON.parse:

JSON.parse(json_string, symbolize_names: true)

This will make the keys symbols, which means you cannot use strings as the key when accessing the hash.

like image 145
Michelle Tilley Avatar answered Dec 22 '22 15:12

Michelle Tilley