Prettify JSON data in textarea input in JavaScript?

For this, use JSON.parse() along with JSON.stringify().


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
<link rel="stylesheet" href="">
<textarea id="prettyJSONFormat" cols=100 rows=20></textarea>
<button onclick="printTheJSONInPrettyFormat()">Click The Button To
get the Pretty JSON</button>
   function printTheJSONInPrettyFormat() {
      var badJSON = document.getElementById('prettyJSONFormat').value;
      var parseJSON = JSON.parse(badJSON);
      var JSONInPrettyFormat = JSON.stringify(parseJSON, undefined, 4);
      document.getElementById('prettyJSONFormat').value =

To run the above program, just save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS Code editor.


This will produce the following output −

Now, I am going to put some bad (unformatted) JSON. The sample JSON data is as follows −

After clicking the button, you will get the following sample output i.e. properly formatted JSON −