2 回答

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
這個(gè)答案使用了@calceamenta的想法,但實(shí)現(xiàn)了實(shí)際的削減邏輯:
def recursive_reduce(obj):
if isinstance(obj, (float, str, int, bool, type(None))):
return obj
if isinstance(obj, dict):
keys = list(sorted(obj))
obj['...'] = '...'
if len(keys) > 5:
new_keys = keys[:2] + ["..."] + keys[-2:]
else:
new_keys = keys
new_dict = {x:obj[x] for x in new_keys}
for k, v in new_dict.items():
new_dict[k] = recursive_reduce(v)
return new_dict
if isinstance(obj, list):
if len(obj) > 5:
new_list = obj[:2] + ["..."] + obj[-2:]
else:
new_list = obj
for i, v in enumerate(new_list):
new_list[i] = recursive_reduce(v)
return new_list
return str(obj)
test_json = {"works": [1, 2, 3, 4, 5, 6],
"not_affected": [{"1": "1", "2": "2", "3": "3", "4": "4", "5": "5"}],
"1": "1", "2": "2", "3": "3",
"removed": "removed"
}
print("original", test_json)
reduced_log = recursive_reduce(test_json)
print("reduced", reduced_log)
輸出:
original {'works': [1, 2, 3, 4, 5, 6], 'not_affected': [{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}], '1': '1', '2': '2', '3': '3', 'removed': 'removed'}
reduced {'1': '1', '2': '2', '...': '...', 'removed': 'removed', 'works': [1, 2, '...', 5, 6]}
希望這有助于:)

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以使用 def __str__(): 方法覆蓋 python 中字典和列表的字符串表示形式。使用它只是以遞歸方式調(diào)用所有元素上的 print 函數(shù)。它可以有一個(gè)簡(jiǎn)單的樣板,如下所示:
def custom_print(obj):
log_str = ''
if type(obj) == list:
for item in obj:
log_str += custom_print(item)
elif type(obj) == dict:
for k, item in obj.items():
custom_print(item)
使用此自定義日志功能,按照日志文件格式打印到日志文件中。
添加回答
舉報(bào)