Print JSON

Print JSON

by mdineshkumarcs

HTML

<script src="http://documentcloud.github.io/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.io/backbone/backbone-min.js"></script>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<div id="some-id"></div>
<div id="log"></div>

CSS

pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }

JavaScript

(function () {
    if (!console) {
        console = {};
    }
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function (message) {
        if (typeof message == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? output(syntaxHighlight(JSON.stringify(message, undefined, 4))) : String(message)) + '<br />';
        } else {
            logger.innerHTML += message + '<br />';
        }
    }
})();
function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    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() {
    // Init when DOM is Ready
    App.init();
});

var App = {
    init: function() {
       new App.MyView();

    }
}
console.log({
    test: 2
});
App.MyView = Backbone.View.extend({
    el: '#some-id',
    initialize: function() {
        App.MyController.doSomething(this);
    }
});

App.MyController = {
    doSomething: function( myView ) {
        console.log( myView );
        alert('MyView.el: ' + myView.el);
    }
}