Ruby hash keys as a symbol do not work

I am confused by why the key character version does not work in the following example. As indicated, I am using Ruby 1.9.3. This is part of a much larger application, but it can 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

+4
source share
2 answers

JSON, a subset of JavaScript, has no concept of characters. All keys are strings - so when you parse JSON with Ruby, a hash is created with strings as keys.

If you're used to working with Ruby on Rails, you can use es to work with HashWithIndifferentAccess es, which let you use strings or characters for your keys.


[Refresh] As mentioned in akuhn's comments, you can make the JSON module symbolize all keys by passing symbolize_names: true the JSON.parse parameters:

 JSON.parse(json_string, symbolize_names: true) 

This will result in key characters, which means that you cannot use strings as keys when accessing the hash.

+11
source

You can specify JSON to indicate all names

 data = JSON.parse(input, :symbolize_names => true) 
+4
source

All Articles