본문 바로가기

Javascript/Vanilla

정리된 형태의 JSON 출력하기

 const newWindow = window.open('', 'new window')
 const jsonString = JSON.stringify({obj}, null, 2);
 newWindow.document.write(`<pre>${jsonString}</pre>`)

JSON을 화면에 출력하다보면 정리된 형태로 나오지 않고 읽기 힘들게 모두 붙어서 나오는 경우가 있다. 이경우 JSON.stringify를 통하여 JSON 문자열로 변경하고, 이를 <pre> 태그에 넣으면 의도한대로 출력되게 된다.

 

JSON.stringify의 세번째 파라미터인 2는 JSON의 구조에서 들여쓰기를 어떻게 할 것인가를 의미한다. 숫자 2는 두 칸 space를 입력하는 것이고 tab을 원하면 "\t"를 넣어주면 된다.

 

자세한 내용은 아래의 링크를 참조할 것

JSON.stringify() - MDN web docs

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify