Introduction
In JavaScript, there are situations when we wish to pretty-print JSON. In this article, we'll look at how to do it.
How to pretty-print JSON using JavaScript
To pretty-print JSON using JavaScript we can use JSON.stringify()
function:
const jsonobj = {"outcome" : "success", "result" : {"name" : "messaging-sockets", "default-interface" : "external", "include" : [], "socket-binding" : {"messaging" : {"name" : "messaging", "interface" : null, "port" : 5445, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}, "messaging-throughput" : {"name" : "messaging-throughput", "interface" : null, "port" : 5455, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}}}, "compensating-operation" : null};
document.getElementById('frontbackend').value = JSON.stringify(jsonobj,null,'\t');
The output:
{
"outcome": "success",
"result": {
"name": "messaging-sockets",
"default-interface": "external",
"include": [],
"socket-binding": {
"messaging": {
"name": "messaging",
"interface": null,
"port": 5445,
"fixed-port": null,
"multicast-address": null,
"multicast-port": null
},
"messaging-throughput": {
"name": "messaging-throughput",
"interface": null,
"port": 5455,
"fixed-port": null,
"multicast-address": null,
"multicast-port": null
}
}
},
"compensating-operation": null
}
The JSON.stringify()
method converts a JavaScript value to a JSON string, and give us opportunity to format that output string.
Conclusion
In this post, we presented the best way to pretty-print JSON using JavaScript.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}