Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Thu May 11 2023

How to programatically format JSON in JavaScript

In this short guide, we will show how we can easily format our JSON into a beutified output. I got the idea to share this after I implemented the API testing feature on our open source page for our open APIs.

Solution

Let's dive right in to it. We will format this JSON from our weather API

const json = [{"id":5128581,"name":"New York","population":8008278,"lat":40.7142691,"lon":-74.0059729,"country":"USA"},{"id":5115985,"name":"East New York","population":173198,"lat":40.66677,"lon":-73.88236,"country":"USA"},{"id":5106292,"name":"West New York","population":49708,"lat":40.78788,"lon":-74.01431,"country":"USA"},{"id":2272790,"name":"New Yekepa","population":24695,"lat":7.57944,"lon":-8.53778,"country":"Liberia"}]

into a beautified object.

So, let's write some JavaScript - we will use JSON.stringify() function for the solution.

const prettified = JSON.stringify(json, null, 2);

And now our output will look like this instead:

[ { "id": 5128581, "name": "New York", "population": 8008278, "lat": 40.7142691, "lon": -74.0059729, "country": "USA" }, { "id": 5115985, "name": "East New York", "population": 173198, "lat": 40.66677, "lon": -73.88236, "country": "USA" }, { "id": 5106292, "name": "West New York", "population": 49708, "lat": 40.78788, "lon": -74.01431, "country": "USA" }, { "id": 2272790, "name": "New Yekepa", "population": 24695, "lat": 7.57944, "lon": -8.53778, "country": "Liberia" } ]

The argument list is the following:

  • The JSON object
  • Replacer array. Basically the values that you want to keep from the object. I will share an example below.
  • Space, the indentation of the output. In our case, we added 2 spaces.

If we want to use tabs instead of spaces, we can just do like this

const prettified = JSON.stringify(json, null, "\t");

Replacer

If we want to use the replacer, we can do as follows

const prettified = JSON.stringify(json, ["id"], 2);

And then the output would be

[ { "id": 5128581 }, { "id": 5115985 }, { "id": 5106292 }, { "id": 2272790 } ]

Outro

In this guide we shared some nice to know things about the JSON.stringify() function that could be useful if we want to output our JSON on a webpage or perhaps on a log or something similar.

I hope you enjoyed this article, and thanks for reading!

signatureThu May 11 2023
See all our articles