【问题标题】:How to show colors in string generated by json.dump?如何在 json.dump 生成的字符串中显示颜色?
【发布时间】:2020-07-30 22:53:29
【问题描述】:

例如:

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

生成的字符串将被转义,颜色代码将按原样打印。

即使json.dumps(data, ensure_ascii=False) 也无济于事。

注意:我不想为 json 着色使用任何额外的库。

【问题讨论】:

  • 你不能这样打印,也许你的意思是json.dumps
  • @RMPR 是的,对不起
  • 只有键会被着色吗?
  • @ThaerA 值也可能有彩色文本
  • @aiven 值总是字符串吗?还是里面有列表、字典?

标签: python colors terminal-color


【解决方案1】:

尝试(代码注释中的解释):

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)

【讨论】:

    【解决方案2】:

    我正在尝试找到解决此问题的方法。我设法通过结合Thaer A's 解决方案和来自这个answer 的一个解决方案。我将与社区分享。简单地使用 Thaer 解决方案会损坏 json,如果它已转义值,例如: "_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))
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      相关资源
      最近更新 更多