猿问

限制用于日志记录的项目数/json 的长度

我正在开发一个返回JSON的API。我正在记录我的回复,有时JSON只是荒谬地长,基本上堵塞了我的日志文件。有没有一种简洁的方法来减少JSON的长度,纯粹是为了直观地记录数据?(在生产中不起作用)


基本方法是将长度为 5 的数组减少到 [前 2, “...”, 最后 2],将具有 4 个以上项的字典减少到 {前 4 个, “...”: “...”}


下面的代码很丑陋。我知道它应该是一个递归解决方案,以与任意深度的JSON相同的方式减少项目 - 它目前只对深度2这样做。


def log_reducer(response_log):

original_response_log = response_log

try:

    if type(response_log) == dict:

        if len(response_log) >= 4:  # {123456}

            response_log = dict(list(response_log.items())[:4])

            response_log.update({"...": "..."})  # {1234...}

        for key, value in response_log.items():

            if type(value) == list:

                if len(value) >= 5:  # {key:[123456]}

                    new_item = value[:2] + ['...'] + value[-2:]  # {[12...56]}

                    response_log.update({key: new_item})

            if type(value) == dict:

                if len(value) >= 4:  # {key:{123456}}

                    reduced_dict = dict(list(value.items())[:4])

                    reduced_dict.update({"...": "..."})

                    response_log.update({key: reduced_dict})  # {{1234...}}





宝慕林4294392
浏览 134回答 2
2回答

慕盖茨4494581

这个答案使用了@calceamenta的想法,但实现了实际的削减逻辑: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]}希望这有助于:)

尚方宝剑之说

您可以使用 def __str__(): 方法覆盖 python 中字典和列表的字符串表示形式。使用它只是以递归方式调用所有元素上的 print 函数。它可以有一个简单的样板,如下所示: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)使用此自定义日志功能,按照日志文件格式打印到日志文件中。
随时随地看视频慕课网APP

相关分类

Python
我要回答