1

I'm getting a json api back from my javascript request. I able to print the output to console and it looks properly formatted eg

{
  "id": "1",
  "name": "John"
}

but when I print to html page. it looks like this

'{"id": "1", "name": "john"}'

here my javascript file

$(function() {
    //variables
    var functionName = 'getQuotes';

    function LoadData() {
        $.get("http://localhost/quoteapi/api.php?function="+functionName+"&jsonCallback=?", function(data) {
            // console.log(data);
            jsonstr = data.substring(2, data.length-1)
            console.log(jsonstr);
            var jsonPretty = JSON.stringify(jsonstr,null,6);           
        });
    }

    LoadData();      
});

and I want to print to a <p> tag with id of "quote"

<p id="quote"></p>

any help appreciated

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
miatech
  • 2,150
  • 8
  • 41
  • 78
  • Are you saying when you inject that string in the page it changes the case of "John" to "john"? Maybe share more of what you're expecting? – Dan Heberden Feb 01 '19 at 20:47
  • Possible duplicate of [JSON.stringify output to div in pretty print way](https://stackoverflow.com/questions/16862627/json-stringify-output-to-div-in-pretty-print-way) – Daniel Beck Feb 01 '19 at 20:50

2 Answers2

1

use a <pre> tag instead of a <p> tag, or add some CSS to maintain the whitespace formatting you want.

.code {
    font-family: monospace;
    white-space: pre;
}
Unstyled &lt;p&gt; tag
<p>
{
  "id": "1",
  "name": "John"
}
</p>

<hr>
Unstyled &lt;pre&gt; tag
<pre>
{
  "id": "1",
  "name": "John"
}
</pre>

<hr>
Styled &lt;p&gt; tag
<p class="code">
{
  "id": "1",
  "name": "John"
}
</p>
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
  • I though it would be possible to do the formatting from JavaScript so I don't have to create a model html page... – miatech Feb 02 '19 at 03:01
1

In a different way you can replace each '\n' (newline) with a <br> and a space with &nbsp;.

The snippet:

var jsonPretty = JSON.stringify( { "id": "1", "name": "John" } ,null,6);
document.querySelector('#quote').innerHTML = jsonPretty
     .replace(/\n( *)/g, function (match, p1) {
         return '<br>' + '&nbsp;'.repeat(p1.length);
     });


var x = { "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 };
document.querySelector('#newquote').innerHTML = JSON.stringify(x, null, 6)
     .replace(/\n( *)/g, function (match, p1) {
         return '<br>' + '&nbsp;'.repeat(p1.length);
     });
<p id="quote"></p>
---------------------
<p id="newquote"></p>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61