sourcecode

Python에서 JSON 출력 색칠하기

copyscript 2023. 2. 23. 23:01
반응형

Python에서 JSON 출력 색칠하기

python에서는 JSON 오브젝트가 있는 경우obj그럼 할 수 있어요.

print json.dumps(obj, sort_keys=True, indent=4)

이 물체를 예쁘게 프린트하기 위해서요.출력을 더 예쁘게 할 수 있을까요?색깔을 더 추가해 주세요.[1]의 결과처럼

cat foo.json | jq '.'

[1]jqJSON Swiss Army 툴박스: http://stedolan.github.io/jq/

Pygragments를 사용하여 JSON 출력을 색칠할 수 있습니다.가지고 있는 정보에 근거합니다.

formatted_json = json.dumps(obj, sort_keys=True, indent=4)

from pygments import highlight, lexers, formatters
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)

출력 예:

pygments 컬러 코드의 출력 예

Pygments와 Python의 최신 버전에서는 받아들여진 답변이 작동하지 않는 것 같습니다.Pygments 2.7.2+에서는 다음과 같이 할 수 있습니다.

import json
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.web import JsonLexer

d = {"test": [1, 2, 3, 4], "hello": "world"}

# Generate JSON
raw_json = json.dumps(d, indent=4)

# Colorize it
colorful = highlight(
    raw_json,
    lexer=JsonLexer(),
    formatter=Terminal256Formatter(),
)

# Print to console
print(colorful)

pyment에 의존한 rich를 사용하는 것을 좋아하지만 콘솔 색상의 요구를 모두 충족하고 json 자동포맷도 가능합니다.

python3의 경우:

#!/usr/bin/python3
#coding: utf-8

from pygments import highlight, lexers, formatters
import json

d = {"test": [1, 2, 3, 4], "hello": "world"}

formatted_json = json.dumps(d, indent=4)
colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)

언급URL : https://stackoverflow.com/questions/25638905/coloring-json-output-in-python

반응형