title: How to store objects in HTML5 localStorage/sessionStorage
body: <p>I'd like to store a JavaScript object in HTML5 <code>localStorage</code>, but my object is apparently being converted to a string.</p>
  <p>I can store and retrieve primitive JavaScript types and arrays using <code>localStorage</code>, but objects don't seem to work.  Should they?</p>
  <p>Here's my code:</p>
  <pre><code>var testObject = { 'one': 1, 'two': 2, 'three': 3 };
  console.log('typeof testObject: ' + typeof testObject);
  console.log('testObject properties:');
  for (var prop in testObject) {
      console.log('  ' + prop + ': ' + testObject[prop]);
  }
  
  // Put the object into storage
  localStorage.setItem('testObject', testObject);
  
  // Retrieve the object from storage
  var retrievedObject = localStorage.getItem('testObject');
  
  console.log('typeof retrievedObject: ' + typeof retrievedObject);
  console.log('Value of retrievedObject: ' + retrievedObject);
  </code></pre>
  <p>The console output is</p>
  <pre class="lang-none prettyprint-override"><code>typeof testObject: object
  testObject properties:
    one: 1
    two: 2
    three: 3
  typeof retrievedObject: string
  Value of retrievedObject: [object Object]
  </code></pre>
  <p>It looks to me like the <code>setItem</code> method is converting the input to a string before storing it.</p>
  <p>I see this behavior in Safari, Chrome, and Firefox, so I assume it's my misunderstanding of the <a href="http://www.w3.org/TR/webstorage/" rel="noreferrer">HTML5 Web Storage</a> specification, not a browser-specific bug or limitation.</p>
  <p>I've tried to make sense of the <em>structured clone</em> algorithm described in <em><a href="https://html.spec.whatwg.org/multipage/infrastructure.html#infrastructure" rel="noreferrer">2 Common infrastructure</a></em>.  I don't fully understand what it's saying, but maybe my problem has to do with my object's properties not being enumerable (???).</p>
  <p>Is there an easy workaround?</p>
  <hr />
  <p>Update: The W3C eventually changed their minds about the structured-clone specification, and decided to change the spec to match the implementations.  See <em><a href="https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111" rel="noreferrer">12111 – spec for Storage object getItem(key) method does not match implementation behavior</a></em>. So this question is no longer 100% valid, but the answers still may be of interest.</p>