Categories
JavaScript Answers

How to prettify JSON data in text area input with JavaScript?

Spread the love

Sometimes, we want to prettify JSON data in text area input with JavaScript.

In this article, we’ll look at how to prettify JSON data in text area input with JavaScript.

How to prettify JSON data in text area input with JavaScript?

To prettify JSON data in text area input with JavaScript, we use the JSON.stringify method.

For instance, we write

<textarea id="myTextArea" cols="50" rows="10"></textarea>
<button>Pretty Print</button>

to add a text area and a button.

Then we write

const button = document.querySelector("button");

button.onclick = () => {
  const ugly = document.getElementById("myTextArea").value;
  const obj = JSON.parse(ugly);
  const pretty = JSON.stringify(obj, undefined, 4);
  document.getElementById("myTextArea").value = pretty;
};

to select the button with querySelector.

And then we set button.onclick to a function that formats the JSON by calling JSON.parse to parse the ugly JSON string.

Next we call JSON.stringify with obj and 4 to format the string with 4 spaces for indentation.

And then we assign the formatted pretty JSON string back to the text area.

Conclusion

To prettify JSON data in text area input with JavaScript, we use the JSON.stringify method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.