2011-05-31 66 views
1

我想用webpy查询MySQL数据库。从SQL查询中,我得到以下内容。如何使用webpy将MySQL查询格式化为JSON?

<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字符串中?

回答

1

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

使用这个存储对象作为参数我没有测试,但你说它在查询中没有日期时有效,我认为这应该起作用。 (有关扩展编码器对象的信息,请参阅json模块docs)。

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) 
0

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

import time 
result.mytime = time.mktime(result.mytime.utctimetuple()) 
+0

仅供参考,我不知道这是如何工作与时区。抱歉。 – icktoofay 2011-05-31 05:02:48