ActiveSupport :: JSON decodes a hash, losing characters

I am trying to serialize and deserialize a hash. When the hash is canceled, the keys are de-symbolized; for example, no more: one, rather "one".

From the rails console:

>>h = { :one =>1, :two => "two"} {:one=>1, :two=>"two"} >>j = ActiveSupport::JSON.encode(h) "{\"one\":1,\"two\":\"two\"}" >>h2 = ActiveSupport::JSON.decode(j) {"one"=>1, "two"=>"two"} >>h2[:one] nil >>h[:one] 1 

Now I switched to using Marshal.dump / load. However, I wanted to drop it there to find out if there is a way to save this in JSON (read-only).

+5
json ruby ruby-on-rails
Mar 04 '11 at 15:00
source share
2 answers
 h2 = ActiveSupport::JSON.decode(j).symbolize_keys 
+8
Mar 04 2018-11-11T00:
source share

JSON.parse(j, {:symbolize_names => true}) should be a little better, because it (I suppose) never creates string keys in the first place and, therefore, saves memory for large hashes with repeated often repeated keys

+16
Oct 10 '12 at 17:40
source share



All Articles