Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Leventix, thank you for your answer.</p> <p>The <strong>Marshal.load(Marshal.dump(h))</strong> method probably has the most integrity of the various methods because it preserves the original key types <em>recursively</em>.</p> <p>This is important in case you have a nested hash with a mix of string and symbol keys and you want to preserve that mix upon decode (for instance, this could happen if your hash contains your own custom objects in addition to highly complex/nested third-party objects whose keys you cannot manipulate/convert for whatever reason, like a project time constraint).</p> <p>E.g.:</p> <pre><code>h = { :youtube =&gt; { :search =&gt; 'daffy', # nested symbol key 'history' =&gt; ['goofy', 'mickey'] # nested string key } } </code></pre> <p><strong>Method 1</strong>: JSON.parse - symbolizes all keys recursively => Does not preserve original mix</p> <pre><code>JSON.parse( h.to_json, {:symbolize_names =&gt; true} ) =&gt; { :youtube =&gt; { :search=&gt; "daffy", :history =&gt; ["goofy", "mickey"] } } </code></pre> <p><strong>Method 2</strong>: ActiveSupport::JSON.decode - symbolizes top-level keys only => Does not preserve original mix</p> <pre><code>ActiveSupport::JSON.decode( ActiveSupport::JSON.encode(h) ).symbolize_keys =&gt; { :youtube =&gt; { "search" =&gt; "daffy", "history" =&gt; ["goofy", "mickey"] } } </code></pre> <p><strong>Method 3</strong>: Marshal.load - preserves original string/symbol mix in the nested keys. PERFECT!</p> <pre><code>Marshal.load( Marshal.dump(h) ) =&gt; { :youtube =&gt; { :search =&gt; "daffy", "history" =&gt; ["goofy", "mickey"] } } </code></pre> <p>Unless there is a drawback that I'm unaware of, I'd think Method 3 is the way to go.</p> <p>Cheers</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload