JSFiddle - React, Tailwind, and code Playground
JSON object formatting
by tonytlwu
HTML
<div id="result"></div>
CSS
body {
font-family: monospace;
font-size: 0.9em;
}
.key {
color: purple;
}
.number {
color: blue;
}
.string {
color: orange;
}
.boolean {
color: red;
}
.null {
color: green;
}
JavaScript
const data = {
a: 'hi',
b: [{
foo: 'bar,how,are",you"'
}, 1, 2, [3, 4]],
c: {
s: 1
},
e: null,
f: false,
g: 'abc\n\nX\b"YZ\r\n\b'
};
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 1);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
function prettyPrint(json) {
if (typeof json === 'string') {
return `"${json.replace(/"/g, '\\"')}"`;
}
if (typeof json !== 'object') {
return json;
}
if (json === null) {
return null;
}
const result = [];
if (Array.isArray(json)) {
result.push('[');
result.push(json.map((item) => {
return prettyPrint(item);
}).join(', '));
result.push(']');
return result.join('');
}
result.push('{');
result.push(Object.keys(json).map((key) => {
return `"${key}": ${prettyPrint(json[key])}`;
}).join(', '));
result.push('}');
return result.join('');
}
const formatJSON = (data) =>
JSON.stringify(data, null, '\b')
.split('\b')
.map(s =>
(s.slice(-1) === ',' ? s + ' ' : s)
.replace(/,\n$/, ', ')
.replace(/\{\n/, '{')
.replace(/\n\}/, '}')
.replace(/\[\n/, '[')
.replace(/\n\]/, ']')
.replace(/\n$/, '')
).join('')
document.getElementById('result').innerHTML = formatJSON(data);