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 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