From 740b2eab607d4ca3d19ab4e2418759e43a2898e8 Mon Sep 17 00:00:00 2001 From: Alejandro Sirgo Rica Date: Tue, 9 Jul 2024 11:01:05 +0200 Subject: utils: place dictionary and list at the end of the json tree Place dictionaries and lists at the end of the payload to improve readability when it has a lot of nested components. Remove and add again every element of type list or dict within a dict or list in the payload. Python dictionaries preserve insertion order from 3.7 onwardsi so it is safe to reorder them by removing and readding an element. --- cli/utils.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) (limited to 'cli/utils.py') diff --git a/cli/utils.py b/cli/utils.py index 49fbddb..56fe723 100644 --- a/cli/utils.py +++ b/cli/utils.py @@ -29,10 +29,27 @@ def ips_in_scope(scope): ips += ips_in_scope(child) return ips +def reorder_json_tree(payload): + if isinstance(payload, list): + elements = payload[:] + for val in elements: + if isinstance(val, (dict, list)): + payload.remove(val) + payload.append(val) + reorder_json_tree(val) + elif isinstance(payload, dict): + keys = list(payload.keys()) + for k in keys: + val = payload[k] + if isinstance(val, (dict, list)): + del payload[k] + payload[k] = val + reorder_json_tree(val) def print_json(text): payload = json.loads(text) - print(json.dumps(payload, sort_keys=True, indent=2)) + reorder_json_tree(payload) + print(json.dumps(payload, indent=2)) def check_address(addr): try: -- cgit v1.2.3-18-g5258