Tired of the one-liner JSON output, well no more! Utilize JSON.stringify built-in pretty printing. Set the 3rd parameter with your desired spacing level π Bam, instant GLAMβ¨
const protein = {steak: 'π₯©', bacon: 'π₯'};
JSON.stringify(protein);
// {"steak":"π₯©","bacon":"π₯"}
JSON.stringify(protein, null, 2);
/*
{
"steak": "π₯©",
"bacon": "π₯"
}
*/
But the Tab folks are like how about us?? Donβt worry, you can also pass β\tβ for tab level spacing π
const protein = {steak: 'π₯©', bacon: 'π₯'};
JSON.stringify(protein, null, "\t");
/*
{
"steak": "π₯©",
"bacon": "π₯"
}
*/
The 3rd parameter of the JSON.stringify is used to control the spacing. Itβs what gives you that pretty string output.
It allows 2 types of arguments: Number and String.
You can use any number from 0 to 10 as your indentation.
const protein = {steak: 'π₯©', bacon: 'π₯'};
JSON.stringify(protein, null, 1);
/*
{
"steak": "π₯©",
"bacon": "π₯"
}
*/
Alternatively, you can use a string as your indentation. It allows a maximum of 10 characters. If you try to pass more than 10, it will just use the first 10 characters. So donβt try to beat the system π
const protein = {steak: 'π₯©', bacon: 'π₯'};
JSON.stringify(protein, null, "I π");
/*
{
I π"steak": "π₯©",
I π"bacon": "π₯"
}
*/
The 2nd parameter is also called the replacer parameter. You can use it to transform the result.
It allows 2 types of arguments: Array and Function.
I want to show you something really interesting when you pass in an array. You can use it to cherry pick the key-value pair that you want to output.
const protein = {
steak: 'π₯©',
bacon: 'π₯',
pop: 'π₯€',
tea: 'π΅',
shrimp: 'π€',
};
JSON.stringify(protein, ['steak', 'pop'], 2);
/*
{
"steak": "π₯©",
"pop": "π₯€"
}
*/
The replacer is called for each item. So you can also pass in a function. This means you can loop over each item and with each pass, manipulate with the logic defined in your function.
Hereβs an example, where I skip over the properties where the value is not a string. In other words, I only want to show the items where the value is a number.
const protein = {
steak: 'π₯©',
calorie: 271,
bacon: 'π₯',
sodium: 58,
};
const replacer = function(key, value) {
if(typeof value !== "string") {
return value
}
return undefined;
}
JSON.stringify(protein, replacer, 2);
/*
{
"calorie": 271,
"sodium": 58
}
*/
#json #javascript