为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

宝慕林4294392 2022-08-02 18:29:35
我正在开发一个返回JSON的API。我正在记录我的回复,有时JSON只是荒谬地长,基本上堵塞了我的日志文件。有没有一种简洁的方法来减少JSON的长度,纯粹是为了直观地记录数据?(在生产中不起作用)基本方法是将长度为 5 的数组减少到 [前 2, “...”, 最后 2],将具有 4 个以上项的字典减少到 {前 4 个, “...”: “...”}下面的代码很丑陋。我知道它应该是一个递归解决方案,以与任意深度的JSON相同的方式减少项目 - 它目前只对深度2这样做。def log_reducer(response_log):original_response_log = response_logtry:    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...}}
查看完整描述

2 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

这个答案使用了@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]}

希望这有助于:)


查看完整回答
反对 回复 2022-08-02
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

您可以使用 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)

使用此自定义日志功能,按照日志文件格式打印到日志文件中。


查看完整回答
反对 回复 2022-08-02
  • 2 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号