无法从Cherrypy将datetime序列化为JSON

2024-05-18 08:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图发送一个记录列表来响应Ajax查询。除非当我的进程因错误datetime.date(2011, 11, 1) is not JSON serializable而失败时,结果中包含datetime字段,否则这很有效。

我试图将找到的答案与CherryPy documentation中的指令结合起来,使用自定义json输出编码器,但我不清楚该函数必须具有什么签名。我写的函数是:

 def json_encoder(thing):

      if hasattr(thing, 'isoformat'):
           return thing.isoformat()
      else:
           return str(thing)

现在,任何使用json输出(即使输出中没有datetime)的都会给我一个错误TypeError: json_encoder() takes exactly 1 argument (0 given)。但是如果编码器不接受参数,它如何接收要编码的对象?

(另外,我假设我使用str(thing)作为默认的编码方法是错误的,这应该通过调用json编码的默认处理程序来完成,但我不确定如何调用该方法)。


Tags: 函数json编码encoder列表datetimereturn进程