Search code examples
javascriptjqueryjsonajaxpretty-print

How can I display the data from the JSON on my webpage?


I am writing a script that sends an ajax request. The Cloud seems to response with the JSON, but how can I display the data from the JSON on my webpage?

Here the link for the pretty printed JSON.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
        <body>
            <button onclick="myFunctionPost()">Start</button>
            <script>
            function myFunctionPost() {
                jQuery.ajax( {
                    url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_77877E443B666B7FED2F?$format=json',
                    type: 'POST',
                    crossDomain: true,
                    dataType: 'jsonp',
                    success: function( response ) {
                        console.log(response);
                    }, 
                    error : function(error) {
                        console.log(error);
                    }   
                } );
            }
            </script>
        </body>
</html>


Solution

  • To achieve this you can use JSON.stringify() space argument. You will also need to wrap the output with <pre> </pre> will preserve the line spacing.

    function myFunctionPost() {
      $.ajax( {
        url: 'https://jsonplaceholder.typicode.com/posts',
        type: 'GET',
        success: function(response) {
          $('#pp').html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
        }, 
        error: function(error) {
          console.log(error);
        }   
      });
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        </head>
            <body>
                <button onclick="myFunctionPost()">Start</button>
                <p id="pp"></p>
                
            </body>
    </html>

    Source: Does jQuery have a JSON/javascript object to HTML pretty print function similar to PHP's var_dump?