Coloring JSON output in python
You can use Pygments to color your JSON output. Based on what you have:
formatted_json = json.dumps(obj, sort_keys=True, indent=4)
from pygments import highlight, lexers, formatters
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)
Output example:
The accepted answer doesn't seem to be working with more recent versions of Pygments and Python. So here's how you can do it in Pygments 2.7.2+:
import json
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.web import JsonLexer
d = {"test": [1, 2, 3, 4], "hello": "world"}
# Generate JSON
raw_json = json.dumps(d, indent=4)
# Colorize it
colorful = highlight(
raw_json,
lexer=JsonLexer(),
formatter=Terminal256Formatter(),
)
# Print to console
print(colorful)
I like using rich which has a dependency on pyments, but it covers all your console coloring needs, it also autoformats json: