Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveSupport::JSON decode hash losing symbols

I'm trying to serialize and deserialize a hash. When the hash is deserailized, the keys are de-symbolized; e.g. not more :one, rather "one".

From 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

I've switched to using Marshal.dump/load for now. However, I wanted to throw this out there to see if there was a way to keep this in JSON (just for readability).

like image 376
Mark Nadig Avatar asked Mar 04 '11 15:03

Mark Nadig


1 Answers

JSON.parse(j, {:symbolize_names => true}) should be slightly better because it (I assume) never creates string keys in the first place and hence conserves memory for large hashes with the same keys repeated often

like image 133
Tim Cull Avatar answered Sep 27 '22 20:09

Tim Cull