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

2
  • 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? Commented Feb 1, 2019 at 20:47
  • Possible duplicate of JSON.stringify output to div in pretty print way Commented Feb 1, 2019 at 20:50

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

I though it would be possible to do the formatting from JavaScript so I don't have to create a model html page...
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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.