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.
master
Alejandro Sirgo Rica 2024-07-09 11:01:05 +02:00
parent 6f9da3fdbb
commit 740b2eab60
1 changed files with 18 additions and 1 deletions

View File

@ -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: