aiven
aiven

Reputation: 4323

How to show colors in string generated by json.dump?

for example:

data = {'\u001b[31mKEY\u001b[0m': 'value'}
print(json.dumps(data))

Generated string will be escaped and color codes will be printed as is.

Even json.dumps(data, ensure_ascii=False) didn't help.

Note: I don't want to use any extra lib for json colorization.

Upvotes: 3

Views: 906

Answers (2)

Károly Szabó
Károly Szabó

Reputation: 1273

I was trying the find the solution for this problem. I managed to solve it with combining Thaer A's solution and one from this answer. I will share it back with the community. Simply using Thaer solution would corrupt the json if it has escaped values like: "_id": "b'\\xa9q\\xa2\\x14\\xfd\\\\\"\\x90'"

import re, json

ANSI_OR_OTHER_REGEX = re.compile(r'(?P<ansi>\\u001b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]))|(?P<other>(?:.|\n)+?)')
def convert_ansi_back(s):
    return "".join(
        (ansi.encode('utf-8').decode('unicode_escape') if ansi else other)
        for ansi, other in ANSI_OR_OTHER_REGEX.findall(s)
    )

def formatted(json_obj):
    return convert_ansi_back(json.dumps(json_obj, indent=2, sort_keys=True))

data = {'\u001b[31mREDKEY\u001b[0m': 'value\u001b[32m partly green\u001b[0m'}
print(formatted(data))

Result:

enter image description here

Upvotes: 0

Thaer A
Thaer A

Reputation: 2323

Try (explanation in code comment):

import json
data = {'\u001b[31mKEY\u001b[0m': ['value','\u001b[31mVALUE\u001b[0m']}
jdump = json.dumps(data)
# encoding utf-8 decoding literal unicode
colorful =  jdump.encode('utf-8').decode('unicode_escape')
print(colorful)

Upvotes: 3

Related Questions