JSONEncoder不处理列表

2024-10-01 13:41:08 发布

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

我有一个深度嵌套的数据结构和大量的列表。我想数数列表而不是显示所有的内容。在

class SummaryJSONEncoder(json.JSONEncoder):
    """
    Simple extension to JSON encoder to handle date or datetime objects
    """
    def default(self, obj):
        func = inspect.currentframe().f_code
        logger.info("%s in %s:%i" % ( 
            func.co_name, 
            func.co_filename, 
            func.co_firstlineno
        ))
        logger.info('default %s', type(obj))
        if isinstance(obj, (datetime.datetime, datetime.date,)):
            return obj.isoformat()
        if isinstance(obj, (list, tuple, set,)):
            return "count(%s)" % len(obj)
        else:
            logger.info('Falling back for %s', type(obj))
            return super(SummaryJSONEncoder, self).default(obj)
    def encode(self, obj):
        func = inspect.currentframe().f_code
        logger.info("%s in %s:%i" % ( 
            func.co_name, 
            func.co_filename, 
            func.co_firstlineno
        ))
        return super(SummaryJSONEncoder, self).encode(obj)

集合似乎编码正确,但列表和元组不会屈从于我的意愿。在

^{pr2}$

我不知道,但看起来列表和元组在其他地方处理,没有传递给默认方法。以前有人需要这样做吗?在


Tags: toselfinfoobjdefault列表datetimedate
1条回答
网友
1楼 · 发布于 2024-10-01 13:41:08

这似乎有用

class SummaryJSONEncoder(json.JSONEncoder):
"""
Simple extension to JSON encoder to handle date or datetime objects
"""
def default(self, obj):
    if isinstance(obj, (datetime.datetime, datetime.date,)):
        return obj.isoformat()
    if isinstance(obj, (list, tuple, set,)):
        return "count(%s)" % len(obj)
    else:
        return super(SummaryJSONEncoder, self).default(obj)
def _iterencode_list(self, obj, x):
    if isinstance(obj, (list, tuple, set,)):
        return self.default(obj)
    return super(SummaryJSONEncoder, self)._iterencode_list(obj, x)

代码跟踪是。在

^{pr2}$

我希望这对某人有帮助:-)

相关问题 更多 >