How to pretty print json using javascript?

In this article, we will take a look at:

JSON means JavaScript Object Notation. Stringify() is the native implementation of pretty-printing. It pretty prints the third argument and determines the spacing to be used.

Example

let a = {
   name: "A",
   age: 35,
   address: {
      street: "32, Baker Street",
      city: "Chicago"
   }
}
console.log(JSON.stringify(a, null, 4))

Output

{
   "name": "A",
   "age": 35,
   "address": {
      "street": "32, Baker Street",
      "city": "Chicago"
   }
}

It is important to note that we used a JSObject here. This is also fine for JSON strings, but they must first be parsed using JSON.parse to become JS objects.

Example

let jsonStr = '{"name":"A","age":35,"address":{"street":"32, Baker Street","city":"Chicago"}}'
console.log(JSON.stringify(JSON.parse(jsonStr), null, 2))

Output

{
   "name": "A",
   "age": 35,
   "address": {
      "street": "32, Baker Street",
      "city": "Chicago"
   }
}

 

 

Exit mobile version