Windows CMD - cmd에서 JSON 출력문 보기 좋게 출력하기
방법 1. JQ 라이브러리 사용
JQ 라이브러리를 이용하면 간편하게 쉘에서 출력 될 json 문자를 보기 좋게 formatting 할 수 있다.
단, 출력될 문장이 전부 json 형태여야 한다.
설치
windows 11 기준 cmd.exe 실행 후 아래 명령어 바로 실행
1
winget install jqlang.jq
설치 완료 후 살향즁안 cmd 창을 종료하고 다시 실행해야 사용이 가능하다.
사용
1
echo {"name": "erum", "pwd": "bimil", "memo": "heung"} | jq .
- 실행 출력
1 2 3 4 5
{ "name": "erum", "pwd": "bimil", "memo": "heung" }
방법 2. python 스크립트 생성 / 실행
파이썬을 설치한 후 작성한 파이썬 스크립트를 실행하여 json 포맷에만 색상과 줄바꿈을 입혀 보기 좋게 출력하는 방법
0. python 설치
위의 블로그를 참고하여 python을 설치한다.
installer 진행시 install now로 진행해버리면 환경 변수를 직접 등록해줘야 하는 번거로움이 생기니 customize installation를 선택하여 설치 중 환경변수가 등록 되도록 확인해주는것이 좋다!
만약 install now로 설치를 한 경우 installer를 다시 실행해서 설치 수정 과정을 진행하면 installer가 환경변수를 등록하도록 선택하는 과정이 등장하므로 이런 방법을 사용할 수도 있다.
설치 확인
1
python --version
python -v를 입력하게 되면 python 쉘로 진입되므로 ctrl + z 또는 ctrl + d를 눌러서 빠져나오면 된다.
1. colorama 라이브러리 추가
1
pip install colorama
2. 스크립트 작성
json-formatter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import re
import json
import sys
from colorama import init, Fore, Style
init(autoreset=True)
def colorize_json(parsed_json, indent=0):
""" JSON 객체를 색상화된 문자열로 변환 """
spaces = ' ' * indent
result = ''
if isinstance(parsed_json, dict):
result += '{\n'
for key, value in parsed_json.items():
colored_key = f"{Fore.CYAN}\"{key}\"{Style.RESET_ALL}"
colored_value = colorize_json(value, indent + 4)
result += f"{spaces} {colored_key}: {colored_value},\n"
result = result.rstrip(',\n') + '\n' + spaces + '}'
elif isinstance(parsed_json, list):
result += '[\n'
for item in parsed_json:
colored_item = colorize_json(item, indent + 4)
result += f"{spaces} {colored_item},\n"
result = result.rstrip(',\n') + '\n' + spaces + ']'
elif isinstance(parsed_json, str):
result += f"{Fore.GREEN}\"{parsed_json}\"{Style.RESET_ALL}"
else:
result += f"{Fore.GREEN}{parsed_json}{Style.RESET_ALL}"
return result
def extract_and_format_json(log):
# JSON 패턴 정의 (간단한 중첩을 처리할 수 있도록 수정)
json_pattern = r'\{(?:[^{}]*|\{(?:[^{}]*|\{[^{}]*\})*\})*\}'
def replace_json(match):
json_str = match.group(0)
try:
parsed_json = json.loads(json_str)
colored_json = colorize_json(parsed_json)
return colored_json
except json.JSONDecodeError:
return json_str
# 로그에서 JSON 패턴을 찾아 포맷하여 교체
formatted_log = re.sub(json_pattern, replace_json, log)
return formatted_log
if __name__ == "__main__":
# 표준 입력으로부터 로그 읽기
log = sys.stdin.read()
# JSON 추출 및 포맷
formatted_log = extract_and_format_json(log)
print(formatted_log)
동작 테스트
1
2
3
4
echo '2023-07-09 12:00:00 INFO Some log message
2023-07-09 12:01:00 INFO {"key1": "value1", "key2": 123, "key3": {"nestedKey": "nestedValue"}}
2023-07-09 12:02:00 ERROR An error occurred
2023-07-09 12:03:00 INFO {"anotherKey": "anotherValue"}' | python json-formatter.py
- 출력 결과
1 2 3 4 5 6 7 8 9 10 11 12 13
2023-07-09 12:00:00 INFO Some log message 2023-07-09 12:01:00 INFO { "key1": "value1", "key2": 123, "key3": { "nestedKey": "nestedValue" } } 2023-07-09 12:02:00 ERROR An error occurred 2023-07-09 12:03:00 INFO { "anotherKey": "anotherValue" }
3. bat 파일 생성
bat 확장자를 가진 파일을 생성하고 아래 내용을 입력한다.
run/my-json.bat
1
2
@echo off
python C:\Users\xh\Documents\json-formatter\json-formatter\json-formatter.py %*
4. bat 파일 위치를 환경 변수로 등록
생성한 bat 파일이 위치한 디렉터리를 환경 변수로 생성하여 bat 파일 이름만으로 실행될 수 있도록 설정한다.
시스템>정보>고급 시스템>환경 변수진입시스템 변수섹션에서 변수Path편집- 스크립트가 들어있는 경로 추가
C:\Users\xh\Documents\json-formatter\run
5. 테스트
새로운 터미널을 실행하고 아래 명령어를 입력해 잘 동작하는지 확인!
1
2
3
4
echo '2023-07-09 12:00:00 INFO Some log message
2023-07-09 12:01:00 INFO {"key1": "value1", "key2": 123, "key3": {"nestedKey": "nestedValue"}}
2023-07-09 12:02:00 ERROR An error occurred
2023-07-09 12:03:00 INFO {"anotherKey": "anotherValue"}' | my-json
- 실행 출력 값
1 2 3 4 5 6 7 8 9 10 11 12
2023-07-09 12:00:00 INFO Some log message 2023-07-09 12:01:00 INFO { "key1": "value1", "key2": 123, "key3": { "nestedKey": "nestedValue" } } 2023-07-09 12:02:00 ERROR An error occurred 2023-07-09 12:03:00 INFO { "anotherKey": "anotherValue" }
참고한 사이트
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.