Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It is actually possible to modify how a Date object will be serialized into JSON. Combined with the reviver function, a bi-directional solution can be created which will automatically work on serialization and can easily be used on deserialization.</p> <p>First modify the serialization like this:</p> <pre><code>Date.prototype.toJSON = function() { return "{timestamp}+" . this.getTime() } </code></pre> <p>This will change the representation of a Date object into a UNIX timestamp with a prefix as a marker:</p> <pre><code>&gt; json = JSON.stringify({test:new Date()}); "{"test":"{timestamp}1380164268633"}" </code></pre> <p>Then you can create a reviver function which will automatically filter out these values:</p> <pre><code>function json_deserialize_helper(key,value) { if ( typeof value === 'string' ) { var regexp; regexp = /^{timestamp}(\d*)$/.exec(value); if ( regexp ) { return new Date(+regexp[1]); } } return value; } </code></pre> <p>(Credit: This code was basically copied from this answer in a related question: <a href="https://stackoverflow.com/a/14509447/2572897">https://stackoverflow.com/a/14509447/2572897</a>)</p> <p>Now with this setup, deserialization of our result from before will result in a Date object again:</p> <pre><code>&gt; JSON.parse(json, json_deserialize_helper); Object {test: Thu Sep 26 2013 04:57:48 GMT+0200 (CEST)} </code></pre> <p>Or you can choose not to modify the serialization but instead use the regexp to catch the standard serialization format:</p> <pre><code>function json_deserialize_helper(key,value) { if ( typeof value === 'string' ) { var regexp; regexp = /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.exec(value); if ( regexp ) { return new Date(value); } } return value; } </code></pre> <p>Example:</p> <pre><code>&gt; json = JSON.stringify({test:new Date()}) "{"test":"2013-09-26T03:05:26.563Z"}" &gt; JSON.parse(json, json_deserialize_helper) Object {test: Thu Sep 26 2013 05:05:26 GMT+0200 (CEST)} </code></pre>
 

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