Skip to content

Instantly share code, notes, and snippets.

@juancarlospaco
Last active January 10, 2022 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juancarlospaco/358bcefc7df07bdc6b80 to your computer and use it in GitHub Desktop.
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.
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"}))
@juancarlospaco
Copy link
Author

Running:

python3 json_pretty.py

Produces:

{
    "a":       1,

    "b":       false,

    "c":       -1,

    "d":       9.9,

    "longer":  "z"
}

Compare to Normal json.dumps() output:

{"b": false, "a": 1, "longers": "z", "d": 9.9, "c": -1}

What it does

  • Adds 4 Spaces for Indentation.
  • Alphabetically Sort Keys.
  • Justify all properties indenting them to the right.
  • Add 1 Empty Blank New Line after each Key:Value pair.
  • Still Valid JSON, JavaScript Compliant too.
  • Python3 Ready (Remove Function Annotations for Python2 use).

Note:

  • Lots of people told me to do this with pprint.pprint() but I can not find a way to do the same with pprint() only (it outputs something similar to json.dumps only), if you know how comment below.

😸

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment