title: How to reliably hash JavaScript objects?
body: <p>Is there a reliable way to <code>JSON.stringify</code> a JavaScript object that guarantees that the ceated JSON string is the same across all browsers, Node.js and so on, given that the JavaScript object is the same?</p>
  <p>I want to hash JavaScript objects like</p>
  <pre><code>{
    signed_data: object_to_sign,
    signature:   md5(JSON.stringify(object_to_sign) + secret_code)
  }
  </code></pre>
  <p>and pass them around across web applications (e.g. Python and Node.js) and the user so that the user can authenticate against one service and show the next service &quot;signed data&quot; for that one to check if the data is authentic.</p>
  <p>However, I came across the problem that <code>JSON.stringify</code> is not really unique across the implementations:</p>
  <ul>
  <li>In Node.js / V8, <code>JSON.stringify</code> returns a JSON string without unnecessary whitespace, such as '{&quot;user_id&quot;:3}.</li>
  <li>Python's <code>simplejson.dumps</code> leaves some whitespace, e.g. <code>'{&quot;user_id&quot;: 3}'</code></li>
  <li>Probably other stringify implementations might deal differently with whitespace, the order of attributes, or whatever.</li>
  </ul>
  <p>Is there a reliable cross-platform stringify method? Is there a &quot;nomalised JSON&quot;?</p>
  <p>Would you recommend other ways to hash objects like this?</p>
  <p><strong>UPDATE:</strong></p>
  <p>This is what I use as a workaround:</p>
  <pre><code>normalised_json_data = JSON.stringify(object_to_sign)
  {
    signed_data: normalised_json_data,
    signature:   md5(normalised_json_data + secret_code)
  }
  </code></pre>
  <p>So in this approach, not the object itself, but its JSON representation (which is specific to the sigining platform) is signed. This works well because what I sign now is an unambiguous string and I can easily <code>JSON.parse</code> the data after I have checked the signature hash.</p>
  <p>The drawback here is that if I send the whole <code>{signed_data, signature}</code> object as JSON around as well, I have to call <code>JSON.parse</code> twice and it does not look as nice because the inner one gets escaped:</p>
  <pre><code>{&quot;signature&quot;: &quot;1c3763890298f5711c8b2ea4eb4c8833&quot;, &quot;signed_data&quot;: &quot;{\&quot;user_id\&quot;:5}&quot;}
  </code></pre>