JS-Quickie: pretty-printing a JSON object without external dependencies

Ever wanted to properly format a JSON string without external library? JavaScript's native JSON.stringify() provides you with exactly that functionality out of the box.

JS-Quickie: pretty-printing a JSON object without external dependencies

I've been implementing an external API interface recently and during the implementation, one task was to add a log entry to the database for the request and response payload (JSON) and display those payloads inside a user interface. Pretty straightforward.

As those JSON request/response payloads can be a few hundred lines long, it would be a mess to display them just as they are (minified and everything in one line, no spaces and no line breaks).

Of course I could have just searched for an npm package and used that one, but I usually try to install as few additional packages as possible to avoid eventual security issues for such small tasks.

JSON.stringify() to the rescue

After a quick search, I came across JSON.stringify()'s MDN documentation and voilá, it already provides the needed functionality out of the box, no additional library required.

Usually I'm using JSON.stringify() to convert a JavaScript object or value to a string in order to quickly clone an object without copying just the references to that object (read more on references in JavaScript here) or to pass data along with a POST request.

const article = {
  title: "Tesla vs. NIO",
  subtitle: "Apart from the charging infrastructure, which company has the brighter future?"
}

await fetch("https://api.myservice.com/articles", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(article)
})

But as the documentation states, JSON.stringify() accepts up to 3 parameters. Let's see which those additional parameters are and how they can help us in properly formatting our JSON.

The second parameter is the replacer (used to alternate the stringification process and filter/select properties of the value, not discussed in this post right here). We'll pass along null for this parameter, this way all fields will be included.

Before we come to the last parameter, let's see a quick example of how JSON.stringify() formats a string by default:

console.log(JSON.stringify({ name: "Ivan Sieder", address: { country: "Italy" } }))

In our console, we'll see the following string. No formatting, indentation or whatsoever.

{"name":"Ivan Sieder","address":{"country":"Italy"}}"

Now that we've seen how JSON.stringify() works by default, let's see how the last (third) parameter can help us to properly format a JSON string. Here we can either pass a number between 0 and 10 (inclusive) or a string of up to 10 characters.

When passing a number, the JSON value will be formatted and the number will used as the amount of spaces for indentation. If 0 is being passed, the result will be the same as without this parameter. If the value is more than 10, it will be capped at 10 in any case (e.g. if you pass 14, it would be automatically set to 10). In the below example, we're passing the number 2 as the last argument, which instructs JSON.stringify() to format the passed value and use 2 spaces for indentation:

console.log(JSON.stringify({ name: "Ivan Sieder", address: { country: "Italy" } }, null, 2));

In our console, this time we would get back the properly formatted string with indentation and line breaks:

{
  "name": "Ivan Sieder",
  "address": {
    "country": "Italy"
  }
}

As the documentation states, the last parameter can be either a number or a string. If we pass a string instead of a number, this string (or at most the first 10 characters of it) will be used for the indentation. This could be useful for example to make the spaces better visible:

console.log(JSON.stringify({ name: "Ivan Sieder", address: { country: "Italy" } }, null, "··"));

This time, our console again displays a properly formatted JSON value but instead of indenting with spaces, it uses our provided string (dots similar to the ones you might know from your editor or IDE):

{
··"name": "Ivan Sieder",
··"address": {
····"country": "Italy"
··}
}

If you have any further questions, aspects you are unsure with or found anything that is incorrect in this article, don't hesitate to reach out to me on Twitter: @ivansieder