Search code examples
javascripthtmljsonangularjsformatter

How to make a JSON formatter with JS and HTML?


I need a JSON formatter in my web application which is developed using Angular JS and Java.

I basically want such JSON formatter that shows JSON in its formatted view. I wanted formatter because normally when i render my JSON text in html, it is showed just like bunch of texts.

Thats why i wanted to make JSON formatter to show these JSON text in formatted view. It will help users to understand the JSON easily.

In my application user input JSON for different purposes. For example, admin input / modify JSON for dynamic fields generation. JSON text will store in DB. I want to make a common JSON formatter for all the purposes. If not possible different JSON formatter for different operation.

Some people suggest me to use JSON.stringify(). But How can i use this for my purpose? or Any other idea?


Solution

  • JSON.stringify is what you are looking for

    JSON.stringify(jsonObject, null, 4); // stringify with spaces (recommended)
    JSON.stringify(jsonObject, null, '\t'); // stringify with tabs
    

    Real world example:

    <html>
        <body>
            <pre>
                <div id="stringifiedCode">
    
                </div>
            </pre>
        </body>
    </html>
    
    <script type="text/javascript">
    var obj = { "hello" : "world", "Test" : [ "hello" ] };
    document.getElementById('stringifiedCode').innerHTML =JSON.stringify(obj, null, 4);
    </script>