Coder Perfect

In a nice print way, JSON.stringify output to div


I stringify a json object using JSON.stringify.

result = JSON.stringify(message, my_json, 2)

The 2 in the preceding parameter is designed to make the outcome look nice. If I do something like alert, it does this (result). However, I want to output this to the user by appending it inside a div. When I do this I get just a single line showing up. (I don’t think it is working because the breaks and spaces are not being interpreted as html?)

{ "data": { "x": "1", "y": "1", "url": "" }, "event": "start", "show": 1, "id": 50 }

Is there a method to export the JSON.stringify result to a div in a nice print format?

Asked by Alexis

Solution #1

Please make use of the pre> tag.

demo :

Answered by Diode

Solution #2

Ensure that the JSON output is included in a pre> tag.

Answered by Adam

Solution #3

If your pre> tag is displaying a single line of JSON because that’s how the string is already delivered (through an api or a function/page outside of your control), reformat it as follows:


<pre id="json">{"some":"JSON string"}</pre>


    (function() {
        var element = document.getElementById("json");
        var obj = JSON.parse(element.innerText);
        element.innerHTML = JSON.stringify(obj, undefined, 2);

or jQuery:


    function formatJson() {
        var element = $("#json");
        var obj = JSON.parse(element.text());
        element.html(JSON.stringify(obj, undefined, 2));

Answered by thinkOfaNumber

Solution #4

My proposal is based on the following:

Answered by gaetanoM

Solution #5

Complete transparency This package was written by myself, but nodedump,, is another way to export JSON or JavaScript objects in a legible format, replete with the ability to skip parts, collapse them, and so on.

Answered by ragamufin

Post is based on