Skip to content

Instantly share code, notes, and snippets.

@vkbo
Last active July 31, 2021 17:04
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 vkbo/8e3a711bab9f4d321a91ca4af9e38c93 to your computer and use it in GitHub Desktop.
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
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