Last active
July 31, 2021 17:04
-
-
Save vkbo/8e3a711bab9f4d321a91ca4af9e38c93 to your computer and use it in GitHub Desktop.
Encode a Python dictionary to JSON with indentation up to a given level only
This file contains 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
import json | |
def jsonEncode(data, n=0, nmax=0): | |
"""Encode a dictionary, list or tuple as a json object or array, and | |
indent from level n up to a max level nmax if nmax is larger than 0. | |
""" | |
if not isinstance(data, (dict, list, tuple)): | |
return "[]" | |
buffer = [] | |
indent = "" | |
for chunk in json.JSONEncoder().iterencode(data): | |
if chunk == "": # pragma: no cover | |
# Just a precaution | |
continue | |
first = chunk[0] | |
if chunk in ("{}", "[]"): | |
buffer.append(chunk) | |
elif first in ("{", "["): | |
n += 1 | |
indent = "\n"+" "*n | |
if n > nmax and nmax > 0: | |
buffer.append(chunk) | |
else: | |
buffer.append(chunk[0] + indent + chunk[1:]) | |
elif first in ("}", "]"): | |
n -= 1 | |
indent = "\n"+" "*n | |
if n >= nmax and nmax > 0: | |
buffer.append(chunk) | |
else: | |
buffer.append(indent + chunk) | |
elif first == ",": | |
if n > nmax and nmax > 0: | |
buffer.append(chunk) | |
else: | |
buffer.append(chunk[0] + indent + chunk[1:].lstrip()) | |
else: | |
buffer.append(chunk) | |
return "".join(buffer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment