The basic approach
const output = JSON.stringify(data, null, 2);
The third argument controls indentation. A value of 2 is a common choice because it is readable without becoming too wide.
Example
const data = { user: { id: 42, name: "Ada" } };
console.log(JSON.stringify(data, null, 2));{
"user": {
"id": 42,
"name": "Ada"
}
}Common pitfall
If the input is a JSON string instead of an object, parse it first with JSON.parse. If the string is invalid, fix the syntax before trying to pretty print it.