[Javascript] HTML UI에서 Object를 Json 형태로 표현하기

JunMyung Lee·2024년 2월 2일
0

HTML

목록 보기
1/2

Javascript에서 Response로 전달받은 객체를 화면에 표현해야 할때, JSON.stringify를 사용하면 화면에 노출 할 수도있고, pretty하게 정렬되어 노출 할 수도있지만, 문자열만 변경되는것이라 색상이 눈에 안들어 올 수 있다. 이에 따라 CSS를 Key, Value에 따라 변경하여 화면에 표현하면, 훨씬 json 형식으로 보여지게 할 수 있다.

Pretty Print JSON Data in Color - JSFiddle - Code Playground

<pre><code id=account></code></pre>
<pre><code id=planets></code></pre>
pre {
   background-color: ghostwhite;
   border: 1px solid silver;
   padding: 10px 20px;
   margin: 20px; 
   }
.json-key {
   color: brown;
   }
.json-value {
   color: navy;
   }
.json-string {
   color: olive;
   }
if (!library)
  var library = {};

library.json = {
  replacer: function(match, pIndent, pKey, pVal, pEnd) {
    var key = '<span class=json-key>';
    var val = '<span class=json-value>';
    var str = '<span class=json-string>';
    var r = pIndent || '';
    if (pKey)
			r = r + key + '"' + pKey.replace(/[": ]/g, '') + '"</span>: ';
    if (pVal)
      r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
    return r + (pEnd || '');
  },
  prettyPrint: function(obj) {
    var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
    return JSON.stringify(obj, null, 3)
      .replace(/&/g, '&amp;').replace(/\\"/g, '&quot;')
      .replace(/</g, '&lt;').replace(/>/g, '&gt;')
      .replace(jsonLine, library.json.replacer);
  }
};

var account = {
  active: true,
  codes: [48348, 28923, 39080],
  city: "London"
};
var planets = [{
  name: 'Earth',
  order: 3,
  stats: {
    life: true,
    mass: 5.9736 * Math.pow(10, 24)
  }
}, {
  name: 'Saturn',
  order: 6,
  stats: {
    life: null,
    mass: 568.46 * Math.pow(10, 24)
  }
}];
$('#account').html(library.json.prettyPrint(account));
$('#planets').html(library.json.prettyPrint(planets));
profile
11년차 검색개발자 입니다. 여러 지식과 함께 실제 서비스를 운영 하면서 발생한 이슈에 대해서 정리하고 공유하고자 합니다.

0개의 댓글