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

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

<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