0

I have the following code:

<div class="panel panel-default">

    <div class="panel-heading"><strong>Parameters</strong>
    </div>
    {{ctrl.Params | json}}
    <br>
    <div>
        <span class="glyphicon glyphicon-info-sign" ></span>      
    </div>
</div>

Now, what I want to do is print the entire JSON contained in ctrl.GlobalCFTParams in a pretty JSON format. What's happening right now is, it is getting displayed in a continuous fashion. Is there some filter or plugin I can use for this? Thanks!

https://codebeautify.org/jsonviewer - JSON beautified by this link is the kind of JSON I want to print on UI.

sarah
  • 247
  • 1
  • 9
  • 19
  • Possible duplicate of [How can I pretty-print JSON using JavaScript?](https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript) – anoop Jun 16 '17 at 11:33

1 Answers1

0

This fiddle might help you.

<div ng-app="app" ng-controller="ctrl">
    <pre ng-bind-html="json | prettify"></pre>
</div>

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


var app = angular.module("app", ['ngSanitize']);

app.filter('prettify', function () {

    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>';
        });
    }

    return syntaxHighlight;
});
app.controller('ctrl', function ($scope) {
    var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
    $scope.json = JSON.stringify(obj, undefined, 4);
});
Ghazanfar Khan
  • 3,648
  • 8
  • 44
  • 89