Beautify JSON object with built-in JSON.stringify()

You don’t need to write a recursive loop to nice-format an object or an array. There is a JSON.stringify() that you can utilize.

Let’s imagine we have a relatively simple object like this: let o = { a: 1, b: "test", c: [1, 2, 3] };

In its simplest form, to format this object into a string, you would run JSON.stringify(o);. This will produce a string '{"a":1,"b":"test","c":[1,2,3]}'. Now, to make it nicer, one would run:

JSON.stringify(o, null, ' ');

This will produce the next string:

{
 "a": 1,
 "b": "test",
 "c": [
  1,
  2,
  3
 ]
}

The first parameter is the value we want to serialize, and it can be anything. The second parameter is special replacer function that we can use to decide on the returning values of each key. The third one is the whitespace to use for indentation.

Let’s see how we can use the replacer. For example, let’s try to serialize the same object, but this time provide a replacer function:

JSON.stringify(o, function(key, value) {
  if (typeof value === 'number') { 
    return value * 2;
  }
  return value;
}, ' ')

Now the output will be different and all numeric values will be multiplied by 2:

{
 "a": 2,
 "b": "test",
 "c": [
  2,
  4,
  6
 ]
}

Now, if you want to drop the key completely, return undefined. For example,

JSON.stringify(o, function(key, value) {
  if (Array.isArray(value)) { 
    return undefined;
  }
  return value;
}, ' ')
{
 "a": 1,
 "b": "test"
}


Did you know that I made an in-browser image converter, where you can convert your images without uploading them anywhere? Try it out and let me know what you think. It's free.

Leave a Comment

Your email address will not be published. Required fields are marked *