1
광범위한 목록이있는 중첩 된 데이터 구조가 있습니다. 모든 내용을 표시하는 대신 목록을 계산하려고합니다.JSONEncoder가 목록을 처리하지 않습니다.
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)
세트가 제대로 인코딩되는 것처럼 보이지만 목록과 튜플이 내 의지로 구부러지지 않습니다.
>>> json.dumps({'hello': set([]), 'world': [1,2,3], 'snot': (1,2,3,), 'time': datetime.datetime.now()}, indent=4, cls=SummaryJSONEncoder)
2016-10-05 14:07:42,786 (9296) __main__ INFO - encode in <pyshell#56>:20
2016-10-05 14:07:42,789 (9296) __main__ INFO - default in <pyshell#56>:5
2016-10-05 14:07:42,792 (9296) __main__ INFO - default <type 'set'>
2016-10-05 14:07:42,793 (9296) __main__ INFO - default in <pyshell#56>:5
2016-10-05 14:07:42,796 (9296) __main__ INFO - default <type 'datetime.datetime'>
'{\n "world": [\n 1, \n 2, \n 3\n ], \n "hello": "count(0)", \n "snot": [\n 1, \n 2, \n 3\n ], \n "time": "2016-10-05T14:07:42.786000"\n}'
>>>
나는 말할 수는 없지만, 목록 및 튜플 다른 곳에서 처리하고 기본 메서드에 전달되지 않은 것 같습니다. 전에 누구든지이 일을해야 했습니까?