Created
April 23, 2019 00:41
-
-
Save EllieTheYeen/079684754f61ddd9d359f12e94b068e9 to your computer and use it in GitHub Desktop.
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 colorize(a, indent=1, seenobjects=None): | |
if a is True: return color('true') + 'true' + color('reset') | |
if a is False: return color('false') + 'false' + color('reset') | |
if a is None: return color('none') + 'null' + color('reset') | |
if isinstance(a, int): return color('int') + str(a) + color('reset') | |
if isinstance(a, float): return color('float') + str(a) + color('reset') | |
#if seenobjects is None: seenobjects = [] | |
if isinstance(a, basestring): | |
return color('stro') + '"' + color('stri') + json.dumps(a)[1:-1] + color('stro') + '"' + color('reset') | |
if isinstance(a, (list, tuple)): | |
#if a in seenobjects: | |
# raise ValueError('Already seen object of type list or tuple') | |
#seenobjects.append(a) | |
startstring = color('array') + '[' + ('\n' if indent else '') + ' ' * indent | |
joinstring = color('comma') +', ' + ('\n' if indent else '') + (' ' * indent) + color('reset') | |
endstring = ('\n' if indent else '') + (' ' * (indent - 1) if indent else '') + color('array') + ']' + color('reset') | |
return startstring + joinstring.join(colorize(b, indent=indent + 1 if indent else 0, seenobjects=seenobjects) for b in a) + endstring | |
if isinstance(a, dict): | |
out = color('obj') + '{' + color('reset') | |
for key, value in a.iteritems(): | |
out += '\n' if indent else '' | |
out += ' ' * indent | |
out += color('kstro') | |
out += '"' | |
out += color('kstri') | |
out += json.dumps(key)[1:-1] | |
out += color('kstro') | |
out += '"' | |
out += color('colon') | |
out += ': ' | |
out += color('reset') | |
out += colorize(value, indent=indent + 1 if indent else 0) | |
out += color('commo') | |
out += ',' | |
out = out[:-1] | |
out += '\n' if indent else '' | |
out += ' ' * (indent - 1) | |
out += color('obj') | |
out += '}' | |
out += color('reset') | |
return out | |
return str(a) | |
def color(name): | |
if name == 'reset': return '\x1b[0m' | |
return '\x1b[%s;%sm' % colors[name] | |
colors = dict( | |
colon = (0, 31), | |
stro = (0, 32), | |
stri = (0, 33), | |
kstro = (0, 34), | |
kstri = (0, 35), | |
array = (0, 37), | |
obj = (1, 37), | |
true = (1, 32), | |
false = (0, 31), | |
comma = (0, 33), | |
commo = (0, 34), | |
none = (0, 34), | |
coa = (0, 35), | |
int = (0, 36), | |
float = (0, 33), | |
) | |
if __name__ == '__main__': | |
print colorize([None,False,True,0,0.0,'test', [1,2,3, dict(a=1, b=[1,2,3, [4,5,6, 'test a']])]], indent=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment