Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
json color printer
"""Color print JSON objects"""
from collections import OrderedDict
from termcolor import colored, cprint
def quote(value):
return '"' + str(value) + '"'
def print_me(method):
def printer(self):
lines = method(self)
indented_lines = [self.indent + line for line in lines]
print('\n'.join(indented_lines))
return printer
class JsonColorPrinter(object):
INDENT = 2
COLORS = [
'red', 'green', 'yellow',
'blue', 'magenta', 'cyan'
]
def __init__(self, json):
self.json = json
self.depth = 0
self.key = None
self.value = None
def print(self):
cprint('{')
self.depth += 1
return self.iterate(self.json)
@property
def indent(self):
return self.INDENT * self.depth * ' '
@property
def is_scalar(self):
return isinstance(self.value, (int, str, float))
@property
def is_list(self):
return isinstance(self.value, (list, tuple))
@property
def is_dict(self):
return isinstance(self.value, dict)
@property
def color(self):
return self.COLORS[self.depth]
@property
def nudge(self):
return self.indent + self.INDENT * ' '
def iterate(self, node):
for self.key, self.value in node.items():
if self.is_list:
self.vector()
elif self.is_dict:
self.depth += 1
self.open()
self.iterate(self.value)
elif self.is_scalar:
self.scalar()
@print_me
def vector(self):
yield colored(self.key + ': [', 'grey')
for item in self.value:
line = self.nudge + str(quote(item)) + ','
yield colored(line, 'white')
yield colored('],', 'grey')
@print_me
def scalar(self):
key = colored(quote(self.key) + ': ', self.color)
value = colored(quote(self.value) + ',', 'white', attrs=['bold'])
yield key + value
@print_me
def open(self):
yield colored(quote(self.key) + ': ', self.color)
if __name__ == '__main__':
example = OrderedDict({
'foo': 'bar',
'meals': {
'breakfast': [
'eggs',
'bacon'
],
'lunch': [
'pizza',
'beer',
'vodka'
],
},
'numbers': {
'one_thousand': 1000,
'two_hundred': 200
}
})
JsonColorPrinter(example).print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment