반응형
Python에서 JSON 출력 색칠하기
python에서는 JSON 오브젝트가 있는 경우obj
그럼 할 수 있어요.
print json.dumps(obj, sort_keys=True, indent=4)
이 물체를 예쁘게 프린트하기 위해서요.출력을 더 예쁘게 할 수 있을까요?색깔을 더 추가해 주세요.[1]의 결과처럼
cat foo.json | jq '.'
[1]jq
JSON 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와 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
반응형
'sourcecode' 카테고리의 다른 글
ORA-04082: 테이블 레벨 트리거에서 새 참조 또는 오래된 참조가 허용되지 않음 (0) | 2023.02.23 |
---|---|
Wordpress 플러그인 슬라이더 회전 오류 (0) | 2023.02.23 |
ASP를 정지하는 방법JQuery를 사용하기 위해 ID를 변경하는 NET (0) | 2023.02.23 |
React Native에서 누를 때 버튼 스타일 변경 (0) | 2023.02.23 |
jquery를 사용하여 단추를 동적으로 추가하는 방법 (0) | 2023.02.23 |