Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coloring JSON output in python

Tags:

python

json

In python, If I have a JSON object obj, then I can

print json.dumps(obj, sort_keys=True, indent=4)

in order to get a pretty printout of the object. Is it possible to prettify the output even further: add some colors in particular? Something like the result of [1]

cat foo.json | jq '.'

[1] jq the JSON Swiss Army toolbox: http://stedolan.github.io/jq/

like image 493
Dror Avatar asked Sep 03 '14 07:09

Dror


People also ask

How do I make json pretty?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

Does Python use json formatting?

Using JSON formatting techniques in Python, we can convert JSON strings to Python objects, and also convert Python Objects to JSON strings. To use these functionalities, we need to use the json module of Python. The json module comes with the Python standard library.


4 Answers

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:

Output example of pygments colored code

like image 174
arnuschky Avatar answered Oct 13 '22 23:10

arnuschky


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)
like image 21
Haterind Avatar answered Oct 14 '22 01:10

Haterind


I like using rich which has a dependency on pyments, but it covers all your console coloring needs, it also autoformats json: enter image description here

like image 38
MortenB Avatar answered Oct 13 '22 23:10

MortenB


For python3 :

#!/usr/bin/python3
#coding: utf-8

from pygments import highlight, lexers, formatters
import json

d = {"test": [1, 2, 3, 4], "hello": "world"}

formatted_json = json.dumps(d, indent=4)
colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)
like image 1
Olivier Lasne Avatar answered Oct 14 '22 01:10

Olivier Lasne