본문 바로가기

Programming/python

python json을 이쁘게 출력해보자 (pprint module)

`pprint`는 Python의 표준 라이브러리인 `pprint` 모듈의 함수로, "Pretty Print"의 약어입니다. 이 함수는 데이터 구조를 더 보기 좋게 출력하는 도구로 사용됩니다.

일반적으로 `print` 함수를 사용하여 데이터를 출력하면, 데이터 구조가 크거나 복잡할 경우 가독성이 떨어지고 구조를 파악하기 어려울 수 있습니다. `pprint` 함수를 사용하면 이러한 문제를 해결할 수 있습니다.

`pprint` 함수는 데이터를 보기 좋게 인쇄하며, 딕셔너리, 리스트, 튜플 등의 중첩된 데이터 구조를 들여쓰기와 줄바꿈을 사용하여 깔끔하게 출력합니다. 이를 통해 데이터의 계층 구조와 관계를 빠르게 파악할 수 있습니다.

`pprint` 모듈의 `pprint` 함수를 사용하는 방법은 다음과 같습니다:

python
import pprint

data = {
    'name': 'John Doe',
    'age': 30,
    'email': 'john.doe@example.com',
    'address': {
        'city': 'New York',
        'zip': '10001'
    },
    'hobbies': ['reading', 'gaming', 'cooking']
}

# 일반 print
print("일반 print:")
print(data)

# pprint 사용
print("\npprint:")
pprint.pprint(data)



위 코드의 결과는 다음과 같습니다:

일반 print:
{'name': 'John Doe', 'age': 30, 'email': 'john.doe@example.com', 'address': {'city': 'New York', 'zip': '10001'}, 'hobbies': ['reading', 'gaming', 'cooking']}

pprint:
{'address': {'city': 'New York', 'zip': '10001'},
 'age': 30,
 'email': 'john.doe@example.com',
 'hobbies': ['reading', 'gaming', 'cooking'],
 'name': 'John Doe'}



`pprint` 함수를 사용하면 데이터가 보기 좋게 출력되어 구조를 파악하기가 편리해집니다. 따라서 디버깅이나 데이터 분석 등에서 유용하게 활용될 수 있습니다.

반응형