I JSON.stringify
a json object by
result = JSON.stringify(message, my_json, 2)
The 2
in the argument above is su
Consider your REST API returns:
{"Intent":{"Command":"search","SubIntent":null}}
Then you can do the following to print it in a nice format:
<pre id="ciResponseText">Output will de displayed here.</pre>
var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);
My proposal is based on:
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>' + ' '.repeat(p1.length);
});
<div id="newquote"></div>
Make sure the JSON output is in a <pre>
tag.
use style white-space: pre
the <pre>
tag also modifies the text format which may be undesirable.
If this is really for a user, better than just outputting text, you can use a library like this one https://github.com/padolsey/prettyprint.js to output it as an HTML table.
A lot of people create very strange responses to these questions that make alot more work than necessary.
The easiest way to do this consists of the following
In actual code, an example will be (combining all steps together):
var input = document.getElementById("input").value;
document.getElementById("output").value = JSON.stringify(JSON.parse(input),undefined,2);
output.value is going to be the area where you will want to display a beautified JSON.