DEV Community

Gaute Meek Olsen
Gaute Meek Olsen

Posted on • Updated on • Originally published at gaute.dev

How to get JSON.stringify formatted

Today I learned how to get the JSON stringified string to be human-readable, which could be nice when saving the data to a file, with JSON.stringify(value, null, 2).

const characters = [
  {
    name: 'Mario',
    color: 'red'
  },
  {
    name: 'Luigi',
    color: 'green'
  }
];

const oneLine = JSON.stringify(characters) ;
const readable = JSON.stringify(characters, null, 2);

console.log(oneLine);
/* "[{"name":"Mario","color":"red"},{"name":"Luigi","color":"green"}]" */

console.log(readable);
/*
"[
  {
    "name": "Mario",
    "color": "red"
  },
  {
    "name": "Luigi",
    "color": "green"
  }
]"
*/
Enter fullscreen mode Exit fullscreen mode

See how adding 2 as the third parameter helped us. Especially if the list would have been larger. The number 2 is the number of spaces you want. For tab, you can use JSON.stringify(characters, null, '\t').

Top comments (3)

Collapse
 
vishnubaliga profile image
Vishnu Baliga

Good one, what is the second argument supposed to be?

Collapse
 
gautemeekolsen profile image
Gaute Meek Olsen

It's a replacer parameter that could be useful in certain scenarios. It accepts either an array with the properties that should be included or a function where you can change the behavior as you like.

const characters = [
  {
    name: 'Mario',
    color: 'red',
    age: 100
  },
  {
    name: 'Luigi',
    color: 'green',
    age: 95
  }
];

const nameAndAge = JSON.stringify(characters, ['name', 'age'], 2);
console.log(nameAndAge);
/*
"[
  {
    "name": "Mario",
    "age": 100
  },
  {
    "name": "Luigi",
    "age": 95
  }
]"
*/

const darkify = (key, value) => {
  if(key === 'color'){
    return 'dark' + value;
  }
  return value;
}
const darkCharacters = JSON.stringify(characters, darkify, 2);
console.log(darkCharacters);
/*
"[
  {
    "name": "Mario",
    "color": "darkred",
    "age": 100
  },
  {
    "name": "Luigi",
    "color": "darkgreen",
    "age": 95
  }
]"
*/
Collapse
 
vishnubaliga profile image
Vishnu Baliga

That's so cool! TY.
(Suggestion: you could have mentioned about the second-argument in the blog as well.)