JSON.stringify() with line breaks

Let's assume that you define the following object:

jsx
let person = {
    
    name: 'Erik',
    age: 29,
    location: 'Barcelona'
    
} 

If you stringify the object, you'll get a string without line breaks:

jsx
let string = JSON.stringify(person);

console.log(string);
// "{"name":"Erik","age":29,"location":"Barcelona"}"

To keep the string with line breaks, you can use the third parameter of the JSON.stringify() function:

jsx
// Indenting 4 spaces (tab) on each line using the 3rd parameter
let stringWithLineBreaks = JSON.stringify(person, null, 4);

console.log(stringWithLineBreaks);
/*
"{
    "name": "Erik",
    "age": 29,
    "location": "Barcelona"
}"
*/

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.