How To Pretty Print Or Format JSON String In JavaScript

JavaScript

26/09/2022


Unknown to many, JSON.stringify has 2 additional parameters that allow us to format a JSON string.

To start off, you will need to parse the string into a JavaScript object, then back into a JSON string.

JAVASCRIPT
const jsonString =
'{"car":"Audi","pet":"Dog","location":{"city":"Vienna","country":"Austria"}}'
const parsedJsonString = JSON.parse(jsonString) // JavaScript object
const formattedJsonString = JSON.stringify(parsedJsonString, null, 2)
console.log(formattedJsonString)
/**
"{
\"car\": \"Audi\",
\"pet\": \"Dog\",
\"location\": {
\"city\": \"Vienna\",
\"country\": \"Austria\"
}
}"
*/

The 3rd (i.e. space) parameter is of interest to us as it inserts whitespace into the output JSON string. It accepts a number (e.g. 2), which represents the amount of whitespace characters inserted at each line and indentation.


WRITTEN BY

Code and stuff