Skip to content

Instantly share code, notes, and snippets.

@hanayashiki
Created July 18, 2019 04:10
Show Gist options
  • Save hanayashiki/ddd5406857afe7ae1ad8e21180c210e5 to your computer and use it in GitHub Desktop.
Save hanayashiki/ddd5406857afe7ae1ad8e21180c210e5 to your computer and use it in GitHub Desktop.
Truncate long json objects so that it is human readable
import sys
import json
max_item = 3
def visualize(obj: dict):
if isinstance(obj, list):
if len(obj) > max_item:
return [visualize(o) for o in obj[0:max_item] + ["(%d items in total)" % len(obj)]]
else:
return [visualize(o) for o in obj]
elif isinstance(obj, dict):
if len(obj) > max_item:
less_obj = {k: obj[k] for k in list(obj.keys())[0:max_item]}
less_obj["(more)"] = len(obj)
return {k:visualize(less_obj[k]) for k in less_obj}
else:
return {k:visualize(obj[k]) for k in obj}
else:
return obj
while True:
jsonl = input()
print(json.dumps(visualize(json.loads(jsonl)), indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment