JSON Formatter / Beautifier HTML Code


Result:


How to format / beautify JSON:

  • Get JSON string from user.
  • Convert string to JSON array or object.
  • Convert JSON to String using JSON.stringify() function
    Syntax: JSON.stringify(obj, replacer, spaces);
    You need to add minimum 4 spaces between objects.
  • Your result is ready to show.
Get JSON string from user:
<textarea id="json_string" rows="5"></textarea>
Convert String to JSON:
var obj = JSON.parse(STRING);
Convert JSON to String & add spaces between objects:
var str1 = JSON.stringify(obj, undefined, 4);
Show output:
console.log(str1);

Full Source Code:


<div class="form-group">
    <textarea class="form-control data" rows="10"></textarea>
</div>
<button class="btn btn-primary" onclick="format()">FORMAT</button>
<br>
<h4>Result:</h4>
<div class="result"></div>  
<style>
    .string { color: green; }
    .number { color: darkorange; }
    .boolean { color: blue; }
    .null { color: magenta; }
    .key { color: red; }
    
    .result {
        padding: 5px; margin: 5px;
        min-height: 100px;
        outline: 1px solid #ccc;
    }
</style>
<script>
    var obj = JSON.parse(string);
    var str1 = JSON.stringify(obj, undefined, 4);
    output(syntaxHighlight(str1));
    
    function output(inp) {
        document.getElementById('result').appendChild(document.createElement('pre')).innerHTML = inp;
    }
    
    function syntaxHighlight(json) {
        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>';
        });
    }
</script>