无法从Cherrypy将datetime作为JSON序列化 [英] Cannot serialize datetime as JSON from Cherrypy

查看:147
本文介绍了无法从Cherrypy将datetime作为JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发送一个响应于Ajax查询的记录列表。这样做很好,除非结果包含datetime字段,当我的进程失败,错误 datetime.date(2011,11,1)不是JSON可序列化。 b
$ b

我尝试将我发现的答案结合到一个非常类似问题,其中包含 CherryPy文档到使用自定义的json_out编码器,但我不清楚这个函数必须具有什么签名。我写的功能是:

  def json_encoder(thing):

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

和现在使用json_out(即使在输出中没有datetime)给我错误 TypeError:json_encoder()只需要一个参数( 0给定)。但是如果编码器没有参数,那么它如何接收编码的对象?



(另外,我假设我使用 str (事情)作为编码的默认方法是错误的,这应该是通过调用任何json编码的默认处理程序,但我不知道如何调用该方法)。

解决方案

我在类似的情况下做下一个:

  class DecimalEncoder(json.JSONEncoder):
def default(self,obj):
if isinstance(obj,Decimal):
return float(obj)
return json.JSONEncoder.default(self,obj)

在通话中: p>

  json.dumps(my_variable,cls = DecimalEncoder)

所以在你的情况下,它应该像:

  class DateEncoder(json.JSONEncoder )
def default(self,obj):
if hasattr(obj,'isoformat'):
return obj.isoformat()
else:
return str(obj)
return json.JSONEncoder.default(self,obj)


json。转储(my_variable,cls = DateEncoder)


I'm attempting to send a list of records in response to an Ajax query. This works well unless the results include a datetime field when my process fails with the error datetime.date(2011, 11, 1) is not JSON serializable.

I attempted to combine the answer I found to a very similar question here with instructions in the CherryPy documentation to use a custom json_out encoder, but it's not clear to me what signature that function must have. The function I wrote is:

 def json_encoder(thing):

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

and now any use of json_out (even with no datetime in the output) gives me the error TypeError: json_encoder() takes exactly 1 argument (0 given). But if the encoder doesn't take an argument, how does it receive the object to encode?

(Also, I assume my use of str(thing) as the default method of encoding is wrong and that this should be done with a call to whatever the default handler for json encoding is, but I'm not sure how to call that method).

解决方案

I do the next in a similar case:

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return float(obj)
        return json.JSONEncoder.default(self, obj)

and at the call:

json.dumps(my_variable, cls=DecimalEncoder)

So in your case it should be like:

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, 'isoformat'):
            return obj.isoformat()
        else:
            return str(obj)
        return json.JSONEncoder.default(self, obj)


json.dumps(my_variable, cls=DateEncoder)

这篇关于无法从Cherrypy将datetime作为JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆