Last active
January 10, 2022 02:58
-
-
Save juancarlospaco/358bcefc7df07bdc6b80 to your computer and use it in GitHub Desktop.
Pretty-Print JSON from dict to string, very Human-Friendly but still Valid JSON, Python3.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from json import dumps | |
def json_pretty(json_dict: dict) -> str: | |
"""Pretty-Printing JSON data from dictionary to string.""" | |
_json = dumps(json_dict, sort_keys=1, indent=4, separators=(",\n", ": ")) | |
posible_ends = tuple('true false , " ] 0 1 2 3 4 5 6 7 8 9 \n'.split(" ")) | |
max_indent, justified_json = 1, "" | |
for json_line in _json.splitlines(): | |
if len(json_line.split(":")) >= 2 and json_line.endswith(posible_ends): | |
lenght = len(json_line.split(":")[0].rstrip()) + 1 | |
max_indent = lenght if lenght > max_indent else max_indent | |
max_indent = max_indent if max_indent <= 80 else 80 # Limit indent | |
for line_of_json in _json.splitlines(): | |
condition_1 = max_indent > 1 and len(line_of_json.split(":")) >= 2 | |
condition_2 = line_of_json.endswith(posible_ends) and len(line_of_json) | |
if condition_1 and condition_2: | |
propert_len = len(line_of_json.split(":")[0].rstrip()) + 1 | |
xtra_spaces = " " * (max_indent + 1 - propert_len) | |
xtra_spaces = ":" + xtra_spaces | |
justified_line_of_json = "" | |
justified_line_of_json = line_of_json.split(":")[0].rstrip() | |
justified_line_of_json += xtra_spaces | |
justified_line_of_json += "".join( | |
line_of_json.split(":")[1:len(line_of_json.split(":"))]) | |
justified_json += justified_line_of_json + "\n" | |
else: | |
justified_json += line_of_json + "\n" | |
return str("\n\n" + justified_json if max_indent > 1 else _json) | |
if __name__ in '__main__': | |
print(json_pretty({"a": 1, "b": False, "c": -1, "d": 9.9, "longers": "z"})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running:
Produces:
Compare to Normal
json.dumps()
output:What it does ❔
Note:
pprint.pprint()
but I can not find a way to do the same withpprint()
only (it outputs something similar tojson.dumps
only), if you know how comment below.😸