summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAlejandro Sirgo Rica <asirgo@soleta.eu>2024-07-09 11:01:05 +0200
committerAlejandro Sirgo Rica <asirgo@soleta.eu>2024-07-09 16:48:29 +0200
commit740b2eab607d4ca3d19ab4e2418759e43a2898e8 (patch)
treeae11c478dbd4a2277e2c344d6098fb04cde83a7f
parent6f9da3fdbb2905d79151e2e4b6a00b0d35a64d18 (diff)
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.
-rw-r--r--cli/utils.py19
1 files changed, 18 insertions, 1 deletions
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: