How to Pretty Print JSON in HTML with Javascript

How to display and pretty print JSON in HTML with Javascript or React

How to Pretty Print JSON in HTML with Javascript

You can easily pretty print JSON with  JSON.Stringify()

JSON.stringify(value[, replacer[, space]])

We use the third argument

A String or Number object that's used to insert white space into the output JSON string for readability purposes.

Start with an object

const data = {
  color: 'red',
  wheels: 4,
  engine: {
    cylinders: 4,
    size: 2.2
  }
}

To convert it to JSON and pretty print

JSON.stringify(data, null, 2)

If your data is already in JSON format use the following to parse the json first

JSON.stringify(JSON.parse(data), null, 2)

To display this with a react component it might look like the following

const data = {
  color: 'red',
  wheels: 4,
  engine: {
    cylinders: 4,
    size: 2.2
  }
}

const codeBlock = (
  <pre>{JSON.stringify(data, null, 2)}</pre>
);

ReactDOM.render(codeBlock, document.getElementById('your-element-id'));

Example in plain js below

And here is the code

<pre style="background-color: #001f3f"><code id="json-container"></code></pre>
<script>
    const data = {
      color: 'red',
      wheels: 4,
      engine: {
        cylinders: 4,
        size: 2.2
      }
    }
    
    document.getElementById('json-container').innerHTML = JSON.stringify(data, null, 2);
</script>