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.

6
  • 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 != JavaScript, and JSON doesn't have any concept of dates. Commented Dec 30, 2013 at 15:15
  • @T.J.Crowder thanks for the clarification, so how can I have a javascript array with Date objects? Commented Dec 30, 2013 at 15:19
  • basically, use .isoformat(). Date type is not supported in JSON. Commented Dec 30, 2013 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. Commented Dec 30, 2013 at 15:22
  • 1
    Watch out - when you use new Date(...) in JavaScript, the months range 0-11. In python they are 1-12. Commented Dec 30, 2013 at 17:38

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but is there a way to do all of that directly in python?
@Tzach do what? You can't store JavaScript date objects themselves in JSON. They are serialized to the representative strings.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.