Python瓶json_将传递参数转储到默认处理程序函数

2024-06-16 11:07:46 发布

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

在使用瓶子的JSON_转储将数据转换为JSON时,如何将参数传递给默认处理程序函数?

EDIT: I missed a point where I convert the data from json_dumps, back to the previous format using json_loads. The reason I use json_dumps is because i need to convert the datetime format to string

我将MySQL查询的结果作为元组列表:

data = [(u'user1', u'Topic1', datetime.datetime(2015, 8, 3, 23, 55), 2.0, 5), (u'user2', u'Topic2', datetime.datetime(2015, 8, 4, 23, 55), 3.0, 5)]

它包含一些datetime格式的数据。我将这些数据作为对AJAX调用的响应以JSON格式发送,因此我对它执行json_dumps。在

现在,我不能简单地执行json_dumps(data),因为它会给出以下错误:

^{pr2}$

因此,我定义了这个处理函数,并按如下方式使用它:

def dataHandler(obj):
    if isinstance(obj, datetime):
        return obj.strftime('%Y-%m-%d %H:%M')

json_dumps(data, default=dataHandler)

这很好地工作,输出是:

'[["user1", "Topic1", "2015-08-03 23:55", 2.0, 5], ["user2", "Topic2", "2015-08-04 23:55", 3.0, 5]

现在在代码的不同点,对于不同的数据,我需要不同格式的datetime。所以,我重新定义了这个函数:

def dataHandler(obj, showTime='no'):
    if isinstance(obj, datetime):
        if str(showTime).lower() == 'no':
            return obj.strftime('%Y-%m-%d')
        elif str(showTime).lower() == 'yes':
            return obj.strftime('%Y-%m-%d %H:%M')

现在,如果我执行json_dumps(data, default=dataHandler),它会正常工作,将showTime视为no,并给出与上述相同的输出。在

当我试图给它一个论点时,问题就来了:

json_dumps(data, default=dataHandler('Yes'))

它给出了以下错误:

TypeError: datetime.datetime(2015, 8, 10, 23, 55) is not JSON serializable

如何在同一个函数中定义不同的情况?在

谢谢。在


Tags: theto数据函数jsonobjdatadatetime
1条回答
网友
1楼 · 发布于 2024-06-16 11:07:46

您可以使用^{}PEP-318)。在

示例:

def json_handler(show_time=True):
    def decorated(obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%FT%T' if show_time else '%F')
        if isinstance(obj, datetime.date):
            return obj.strftime('%F')
        return repr(obj) # catch-all
    return decorated

然后:

^{pr2}$

编辑

return repr(obj) # catch-all将使用对象的表示而不是拒绝转储它(即:"<object object at 0x7f934f6ef0c0>"而不是{});这可能是需要的,也可能不是。在

别忘了给装饰工打电话!
不这样做(即:json.dumps(data, default=json_handler)而不是json.dumps(data, default=json_handler()))将导致RuntimeError: maximum recursion depth exceeded while calling a Python object或{}。在

相关问题 更多 >