How to use JSON.stringify to output JSON to a div in a pretty print way with JavaScript?

Spread the love

Sometimes, we want to use JSON.stringify to output JSON to a div in a pretty print way with JavaScript.

In this article, we’ll look at how to use JSON.stringify to output JSON to a div in a pretty print way with JavaScript.

How to use JSON.stringify to output JSON to a div in a pretty print way with JavaScript?

To use JSON.stringify to output JSON to a div in a pretty print way with JavaScript, we call it with a 3rd argument.

For instance, we write

<pre id="json"></pre>

to add a pre element.

Then we write

const data = {
  data: {
    x: "1",
    y: "1",
    url: "http://url.com",
  },
  event: "start",
  show: 1,
  id: 50,
};

document.getElementById("json").textContent = JSON.stringify(
  data,
  undefined,
  2
);

to call JSON.stringify with data and 2 to return a JSON string converted from data indented with 2 spaces at each level.

And then we set the textContent of the pre element to the returned JSON string to show it with the indentation.

Conclusion

To use JSON.stringify to output JSON to a div in a pretty print way with JavaScript, we call it with a 3rd argument.

Leave a Reply

Your email address will not be published. Required fields are marked *