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 print is an way of printing JSON object with corrent indentation, tabs and spaces and these can be easy read by developers.

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

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

JSON strify method Convert the Javascript object to json string by add the spaces to JSOn string and print in easy readable format.

Here is an syntax


jsonstring: is an input string to output pretty print replacer: replace the specific values during pretty print length: It is 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 file in native javascript

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

There are multiple ways we can achieve it.

using fetch method to asyncronous read json file

Let’s have a employee.json file which contains 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