Python和JavaScript之间的JSON日期时间

本文翻译自:JSON datetime between Python and JavaScript

I want to send a datetime.datetime object in serialized form from Python using JSON and de-serialize in JavaScript using JSON. 我想使用JSON从Python发送序列化形式的datetime.datetime对象,并使用JSON在JavaScript中反序列化。 What is the best way to do this? 做这个的最好方式是什么?


#1楼

参考:https://stackoom.com/question/1uW4/Python和JavaScript之间的JSON日期时间


#2楼

On python side: 在python方面:

import time, json
from datetime import datetime as dt
your_date = dt.now()
data = json.dumps(time.mktime(your_date.timetuple())*1000)
return data # data send to javascript

On javascript side: 在JavaScript方面:

var your_date = new Date(data)

where data is result from python 其中数据来自python


#3楼

You can add the 'default' parameter to json.dumps to handle this: 您可以将'default'参数添加到json.dumps来处理:

date_handler = lambda obj: (
    obj.isoformat()
    if isinstance(obj, (datetime.datetime, datetime.date))
    else None
)
json.dumps(datetime.datetime.now(), default=date_handler)
'"2010-04-20T20:08:21.634121"'

Which is ISO 8601 format. 这是ISO 8601格式。

A more comprehensive default handler function: 更全面的默认处理函数:

def handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    elif isinstance(obj, ...):
        return ...
    else:
        raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))

Update: Added output of type as well as value. 更新:添加了类型和值的输出。
Update: Also handle date 更新:还处理日期


#4楼

My advice is to use a library. 我的建议是使用一个库。 There are several available at pypi.org. pypi.org上有几个版本。

I use this one, it it works good: https://pypi.python.org/pypi/asjson 我使用这个,它运作良好: https//pypi.python.org/pypi/asjson


#5楼

Using json , you can subclass JSONEncoder and override the default() method to provide your own custom serializers: 使用json ,您可以继承JSONEncoder并覆盖default()方法以提供您自己的自定义序列化程序:

import json
import datetime

class DateTimeJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        else:
            return super(DateTimeJSONEncoder, self).default(obj)

Then, you can call it like this: 然后,你可以像这样调用它:

>>> DateTimeJSONEncoder().encode([datetime.datetime.now()])
'["2010-06-15T14:42:28"]'

#6楼

Late in the game... :) 比赛后期...... :)

A very simple solution is to patch the json module default. 一个非常简单的解决方案是修补json模块的默认值。 For example: 例如:

import json
import datetime

json.JSONEncoder.default = lambda self,obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else None)

Now, you can use json.dumps() as if it had always supported datetime... 现在,您可以使用json.dumps() ,就像它始终支持datetime一样...

json.dumps({'created':datetime.datetime.now()})

This makes sense if you require this extension to the json module to always kick in and wish to not change the way you or others use json serialization (either in existing code or not). 如果您要求json模块的这个扩展始终启动并希望不改变您或其他人使用json序列化的方式(在现有代码中或不在现有代码中),这是有意义的。

Note that some may consider patching libraries in that way as bad practice. 请注意,有些人可能会认为以这种方式修补库是不好的做法。 Special care need to be taken in case you may wish to extend your application in more than one way - is such a case, I suggest to use the solution by ramen or JT and choose the proper json extension in each case. 如果您希望以多种方式扩展您的应用程序,则需要特别小心 - 在这种情况下,我建议使用拉面或JT的解决方案并在每种情况下选择适当的json扩展。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值