In this post, you learn examples of JavaScript

  • How to pretty print JSON object
  • How to read the JSON object
  • Write JSON file

How to pretty print jSON object in Javascript

Pretty print is 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 stringifymethod Convert the Javascript object to json string by adding the spaces to the JSOn string and printing in an easily readable format.

Here is a syntax

JSON.stringify(jsonstring,replacer,length)

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

<script>
  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"}];

  console.log(JSON.stringify(jsonString,null,3));
</script>

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 a fetch example

<script>
fetch("file:///A:/work/w3schools/json/employee.json")
  .then(response => response.json())
  .then(jsonObject => console.log(jsonObject));

</script>

How to write content to JSON in javascript