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, '&').replace(/\\"/g, '"')
.replace(/</g, '<').replace(/>/g, '>')
.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));