0

How can I serialize a python list contains datetime.date objects, to a JSON array of javascript Date objects? For example:

lst = [datetime.date(2013, 12, 30), datetime.date(2013, 12, 31)]
print serialize(lst)
# should print "[new Date(2013, 12, 30), new Date(2013, 12, 31)]"

I've tried json.dumps with a custom handler but the handler can only return serializable objects and not the actual JSON syntax.

Tzach
  • 12,889
  • 11
  • 68
  • 115
  • 2
    You can't have "...a JSON array of JavaScript `Date` objects." You can have a JSON array, *or* you can have a JavaScript array containing `Date` objects. [JSON](http://json.org/) != JavaScript, and JSON doesn't have any concept of dates. – T.J. Crowder Dec 30 '13 at 15:15
  • @T.J.Crowder thanks for the clarification, so how can I have a javascript array with Date objects? – Tzach Dec 30 '13 at 15:19
  • basically, use `.isoformat()`. `Date` type is not supported in JSON. – zs2020 Dec 30 '13 at 15:19
  • @zsong thanks. It's not critical that the array will be JSON, javascript is ok as well. If i use .isoformat I will have to do another pass on the array in javascript to convert the values to `Date` objects and that's something I prefer not to do. – Tzach Dec 30 '13 at 15:22
  • @Tzach You have to do that anyway coz JSON doesn't support Date type. – zs2020 Dec 30 '13 at 15:23
  • 1
    Watch out - when you use `new Date(...)` in JavaScript, the months range 0-11. In python they are 1-12. – Matt Johnson-Pint Dec 30 '13 at 17:38

1 Answers1

0

JavaScript Date objects are json-serialized to strings. However, you can construct a date object from this serialized string. The closest string that the python datetime.date class provides seems to be isoformat.

lst = [datetime.date(2013, 12, 30).isoformat(),
    datetime.date(2013, 12, 31).isoformat()]

On the JavaScript side, these will simply be strings like "2013-12-31". You can construct a date object from that -- new Date("2013-12-30"). It will probably look something like:

lst = JSON.parse(lstJson);
lst.forEach(function (date) {
    var date = new Date(date);
});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Thanks, but is there a way to do all of that directly in python? – Tzach Dec 30 '13 at 15:25
  • @Tzach do *what*? You can't store JavaScript date objects themselves in JSON. They are serialized to the representative strings. – Explosion Pills Dec 30 '13 at 15:28
  • 1
    I doesn't really matter if the array is JSON or javascript, all I need is an output string that looks like the one in the question, so I can embed it into an existing JS code, without iterating over the array in JS. – Tzach Dec 30 '13 at 15:36