In this post, you learn examples in javascript

  • How to pretty print json object
  • How to read JSOn object
  • Write json file

How to pretty print jSON object in Javascript

Pretty printis a way of printing JSON objects with current indentation, tabs, and spaces and these can be easily read by developers.

This will be very useful for the inspection of a JSOn object during debugging.

There are multiple ways we can do it, Using JSON.stringify method

JSON stringify method Convert the Javascript object to json string by adding the spaces to JSOn string and print in an easily readable format.

Here is a syntax


jsonstring: is an input string to output pretty print replacer: replace the specific values during pretty print length: It is the length of white spaces to be inserted with min=2 and max=10

  const jsonString=[{"name":"eric","id":"1"},{"name":"andrew","id":"2"},{"name":"john","id":"3"},{"name":"Flintoff","id":"4"},{"name":"Greg","id":"5"},{"name":"Francis","id":"6"}];

How to read external JSON files in native javascript

It is very easy to read json data files in Javascript.

There are multiple ways we can achieve it.

using fetch method to asynchronous read json file

Let’s have an employee.json file that contains the following data.

    "name": "eric",
    "id": "1"
    "name": "andrew",
    "id": "2"
    "name": "john",
    "id": "3"
    "name": "Flintoff",
    "id": "4"
    "name": "Greg",
    "id": "5"
    "name": "Francis",
    "id": "6"

here is an fetch example

  .then(response => response.json())
  .then(jsonObject => console.log(jsonObject));

How to write content to JSON in javascript