포스트

Ubuntu - bash에서 JSON 출력문 보기 좋게 출력하기

방법 1. JQ 라이브러리 사용

JQ 라이브러리를 이용하면 간편하게 쉘에서 출력 될 json 문자를 보기 좋게 formatting 할 수 있다.

단, 출력될 문장이 전부 json 형태여야 한다.


설치

1
sudo apt-get install jq


사용

1
echo '{"name": "이름", "pwd": "비밀", "memo": "흥"}' | jq .
  • 실행 출력
    1
    2
    3
    4
    5
    
      {
        "name": "이름",
        "pwd": "비밀",
        "memo": "흥"
      }
    



방법 2. python 스크립트 생성, 실행

파이썬을 설치한 후 작성한 파이썬 스크립트를 실행하여 json 포맷에만 색상과 줄바꿈을 입혀 보기 좋게 출력하는 방법

1. python 설치 확인

1
python3 --version
  • 만약 python3 -v 를 입력하게 되면 python3 쉘에 갇히게 되므로 ctrl + d를 눌러 빠져나온다


2. 스크립트 작성

디렉터리 생성

나는 /usr/share/my-custom-libs경로에 파일을 생성하고 관리할 생각이라서 이 경로로 지정

1
mkdir -p /usr/share/my-custom-libs


스크립트 생성

1
vi /usr/share/my-custom-libs/json-formatter.py

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)


3. 테스트

작성한 스크립트가 잘 동작하는지 테스트를 진행

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"}' | python3 /usr/share/my-custom-libs/json-formatter.py
  • 실행 출력 값
    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"
      }
    


4. alias 등록

alias로 명령문을 등록하여 실행하기 쉽게 설정!

1. ~/.bashrc 편집

1
vi ~/.bashrc

파일의 맨 아래에 alias 생성 코드를 입력해준다.

1
2
3
MY_JSON_FORMATTER='python3 /usr/share/my-custom-libs/json-formatter.py'
alias my-str="$MY_JSON_FORMATTER"
alias my-json="$MY_JSON_FORMATTER"


2. ~/.bashrc 변경사항 적용

1
source ~/.bashrc


3. 모든 계정에서 사용할 수 있도록 설정

모든 계정에서 사용하게 하려면 ~/.bashrc에 입력한 alias 내용을 /etc/bash.bashrc 파일에 입력해줘야 한다.

1
sudo vi /etc/bash.bashrc

입력 후 쉘에 다시 로그인하면 적용된다!


5. 테스트

내 경우 my-jsonmy-str로 등록해서 둘 다 테스트

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
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-str

출력 값

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 라이센스를 따릅니다.