在python中使用ASCII颜色打印漂亮的JSON

时间:2014-10-20 06:38:18

标签: python json pretty-print

我希望使用ASCII颜色在python中将命令行打印到JSON。例如,(优秀的)jq实用程序将使用粗体ASCII颜色着色JSON,如下所示:

  • 输入:curl --silent http://coinabul.com/api.php | jq .
  • 输出:
    jq output

有谁知道如何从Python实现这种效果?一些SO问题提供了一些关于使用python中的ASCII颜色的好信息(例如Print in terminal with colors using Python?),但是这种效果需要以不同的方式将漂亮的印刷机械与着色机械相结合。“ p>

3 个答案:

答案 0 :(得分:20)

使用Pygments库:

import json
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import TerminalFormatter

json_object = json.loads('{"foo":"bar"}')
json_str = json.dumps(json_object, indent=4, sort_keys=True)
print(highlight(json_str, JsonLexer(), TerminalFormatter()))

答案 1 :(得分:1)

这应该让你开始(它以蓝色打印键):

import json
import urllib2

# ANSI color terminal escape sequences
OKBLUE = '\033[94m'
ENDC = '\033[0m'

def pretty(keyvals, indent=''):
    print '{'
    for key, val in keyvals.iteritems():
        print '{}  {}"{}"{}:'.format(indent, OKBLUE, key, ENDC),
        if isinstance(val, dict):
            pretty(val, indent + '  ')
        elif isinstance(val, str):
            print '"{}",'.format(val)
        else:
            print '{},'.format(val)
    print indent + '},'

req = urllib2.Request('http://coinabul.com/api.php', headers={
        'User-Agent': 'Mozilla/5.0',
        })

page = urllib2.urlopen(req)
parsed = json.load(page)

pretty(parsed)

答案 2 :(得分:1)

使用https://github.com/willmcgugan/rich

from rich.console import Console
from rich.theme import Theme
from rich.highlighter import RegexHighlighter, _combine_regex
my_theme = Theme(
    {
        "repr.str": "bright_blue",
        "repr.value_str": "green",
    }
)

class ReprHighlighter(RegexHighlighter):
    """Highlights the text typically produced from ``__repr__`` methods."""

    base_style = "repr."
    highlights = [
        r"(?P<tag_start>\<)(?P<tag_name>[\w\-\.\:]*)(?P<tag_contents>[\w\W]*?)(?P<tag_end>\>)",
        r"(?P<attrib_name>[\w_]{1,50})=(?P<attrib_value>\"?[\w_]+\"?)?",
        r"(?P<brace>[\{\[\(\)\]\}])",
        _combine_regex(
            r"(?P<ipv4>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})",
            r"(?P<ipv6>([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})",
            r"(?P<eui64>(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4})",
            r"(?P<eui48>(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})",
            r"(?P<call>[\w\.]*?)\(",
            r"\b(?P<bool_true>True)\b|\b(?P<bool_false>False)\b|\b(?P<none>None)\b",
            r"(?P<ellipsis>\.\.\.)",
            r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[\-\+]?\d+?)?\b|0x[0-9a-fA-F]*)",
            r"(?P<path>\B(\/[\w\.\-\_\+]+)*\/)(?P<filename>[\w\.\-\_\+]*)?",
            r":(?<![\\\w]) (?P<value_str>b?\'\'\'.*?(?<!\\)\'\'\'|b?\'.*?(?<!\\)\'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")",
            r"(?<![\\\w])(?P<str>b?\'\'\'.*?(?<!\\)\'\'\'|b?\'.*?(?<!\\)\'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")",
            r"(?P<uuid>[a-fA-F0-9]{8}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{12})",
            r"(?P<url>(https|http|ws|wss):\/\/[0-9a-zA-Z\$\-\_\+\!`\(\)\,\.\?\/\;\:\&\=\%\#]*)",
        ),
    ]


console = Console(theme=my_theme, highlighter=ReprHighlighter())
json_str = json.dumps(json_object, indent=4, sort_keys=True)
console.print(json_str)

只有value_str被添加到ReprHighlighter