1

我正在尝试使用 webpy 查询 MySQL 数据库。从 SQL 查询中,我得到以下信息。

<Storage {'title': u'Learn web.py', 'done': 0, 'id': 0L, 'mytime': datetime.datetime(2011, 5, 30, 10, 53, 9)}>

我尝试使用json.dumps(data)JSON 格式将数据序列化,但是我收到一个错误,表明数据不可序列化。

我可能会遍历每个键值对并将其放入另一个字典中,但这似乎工作量太大。

关于最佳方法的任何建议?

编辑: 我认为我的问题是因为我有datetime.datetime(2011, 5, 30, 10, 53, 9)数据。我mytime从数据库中删除了该列,一切正常。有没有办法将mytime列包含到 JSON 字符串中?

4

2 回答 2

1

您可以扩展 json.JSONEncoder 来处理日期:

我没有使用 Storage 对象作为参数对此进行测试,但是正如您所说的,当查询中没有日期时它可以工作,我认为这应该可以工作。(有关扩展编码器对象的信息,请参阅 json 模块文档)。

import datetime, json

class ExtendedEncoder(json.JSONEncoder):

    def default(self, o):
        if isinstance(o, datetime.datetime):             
            # If it's a date, convert to a string
            # Replace this with whatever your preferred date format is
            return o.strftime("%Y-%m-%d %H:%M:%S")  

        # Defer to the superclass method
        return json.JSONEncoder(self, o)

那么,如果“结果”是你的存储对象

json_string = json.dumps(result, cls=ExtendedEncoder)
于 2011-06-06T15:59:29.467 回答
0

尝试将其转换为 UNIX 时间戳:

import time
result.mytime = time.mktime(result.mytime.utctimetuple())
于 2011-05-31T05:02:13.047 回答