December 7, 2023

How to pretty print JSON in react?

In React for printing JSON in a pretty format is not that straight forward as angular. In angular, we can use JSON pipe but in React there is no any inbuild react utility we can use for printing JSON in pretty format

let’s see how we can do it

import React from "react";
import "./style.css";
export default function App() {
  const obj1 = {
  return (
      <PrettyPrint jsonObj={obj1} />

function PrettyPrint(props){
  return <pre>{JSON.stringify(props.jsonObj,null,2)}</pre>

As you can see we have created one functional component in that we are using JSON.stringify method which usually used to convert data into string format

But JSON.stringify takes some parameter for manipulating the data

want to know about JSON.stringify in detail then go through this post

Here we have given the third parameter as 2 which includes empty space in the JSON for readability purpose.

Its output will shown like

  "a": {
    "b": {
      "c": 10

For demo,

please checkout this link