Question

My server side will return a JSON string and I need to display it at my Html page. So lets say the string is something like this:

{"FirstChildType":{"FirstGrandChild":{"GrandChildName":"123"},"FirstChildName":"a"},"SecondChildType":{"SecondChildName":"SecondChildABC","SecondChildLastName":"SecondChildXYZ"},"ThirdChildType":null,"FirstName":"ABC","LastName":"XYZ"}

How do I show this in my Html with a nice indention? I tried 'google-code-prettify' but somehow couldn't get this to work like I wanted.

Was it helpful?

Solution

This page here answers it well with JSON.stringfy. See it in JS Fiddle

            function syntaxHighlight(json) {
                if (typeof json != 'string') {
                     json = JSON.stringify(json, undefined, 2);
                }
                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>';
                });
            }

OTHER TIPS

You can use JSON.stringify to format it :

var jsParsed = {"FirstChildType":{"FirstGrandChild":{"GrandChildName":"123"},"FirstChildName":"a"},"SecondChildType":{"SecondChildName":"SecondChildABC","SecondChildLastName":"SecondChildXYZ"},"ThirdChildType":null,"FirstName":"ABC","LastName":"XYZ"};        
var indented = JSON.stringify(g,null,4);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top