본문 바로가기
개발

[Python] json dumps로 예쁘게 출력하기

by 정보알려주는언니 2021. 10. 5.

 

Python으로 api 호출시 응답값을 json으로 받게되는 경우가 있다. 

이때 결과값을 json그대로 print하게되면 아래와같이 json응답값이 한줄로 출력되어 가독성이 매우 떨어지게 된다.

(나는 개발환경이 Pycharm인데, 다른 개발환경은 정상적으로 노출 될 수도있다. )

 

print(result)

tistory api 호출시 응답값 예시이다.

 

 

json 예쁘게 정렬하기


import json
...
print(json.dumps(result, ensure_ascii=False, indent=3))

print시 위와같이 설정해주면된다.

 

result : json 결과값
ensure_ascii : 아스키사용여부 (true일경우 아스키가아닌문자들은 모두 이스케이프문자로 표기됨)
indent : 각 트리별 들여쓰기시, 들여쓰기 탭 갯수

 

결과값은 아래와같이 예쁘게 노출된다. 

{
   "tistory": {
      "status": "200",
      "item": {
         "url": "https://eomcheon.tistory.com",
         "secondaryUrl": "",
         "page": "1",
         "count": "10",
         "totalCount": "120",
         "posts": [
            {
               "id": "1111111",
               "title": "[Python] 티스토리 API 사용하여 글 목록 불러오기",
               "postUrl": "https://eomcheon.tistory.com/126",
               "visibility": "20",
               "categoryId": "963650",
               "comments": "0",
               "trackbacks": "0",
               "date": "2021-10-04 08:00:06"
            }
         ]
      }
   }
}

 


댓글