How to pretty print JSON in JavaScript

Published on in JavaScript

Last updated on

Run JSON.stringify(object, null, 2). Adjust the number for a different level of indentation.

Example:

const object = {
  foo: 'bar',
  ham: {
    spam: [10, 20],
  },
}

JSON.stringify(object)
// {"foo":"bar","ham":{"spam":[10,20]}}

JSON.stringify(object, null, 2)
// {
//   "foo": "bar",
//   "ham": {
//     "spam": [
//       10,
//       20
//     ]
//   }
// }

Read more about JSON.stringify() on MDN