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
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 HashWithIndifferentAccess
es, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With