How to pretty print json using javascript?

Table of Contents

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"
   }
}

 

 

How Lack of Rest Can Impact Your Finances Small Businesses Can Enhance File Management Following these Tips How Much Do Real Estate Agents Spend on Marketing? How to Engage Your Online Audience for Long-Lasting Success Why is Plagiarism Such a Big Deal? Resume Service Review: Why Everyone Should Use It
adbanner