What Is JSON?

JSON stands for JavaScript Object Notation.

JSON is a simple format used to store and exchange data.

It is commonly used when sending data between a server and a web application.

For example, when we fetch data from an API, the data is often sent in JSON format.

Example of JSON

{ "name": "Lokesh", "age": 22, "course": "Java Full Stack" } 

JSON stores data using key-value pairs.

For example:

  • "name" is a key.
  • "Lokesh" is its value.

JSON vs JavaScript Object

JSON looks similar to a JavaScript object, but there are some differences.

JavaScript Object

let user = { name: "Lokesh", age: 22 }; 

JSON

{ "name": "Lokesh", "age": 22 } 

One important difference is that JSON requires property names to be written with double quotes.

JSON.stringify()

JSON.stringify() converts a JavaScript object into a JSON string.

let user = { name: "Lokesh", age: 22 }; let jsonData = JSON.stringify(user); console.log(jsonData); 

Output:

{"name":"Lokesh","age":22} 

This is useful when we need to send JavaScript data in JSON format.

JSON.parse()

JSON.parse() converts a JSON string into a JavaScript object.

let jsonData = '{"name":"Lokesh","age":22}'; let user = JSON.parse(jsonData); console.log(user.name); 

Output:

Lokesh 

Now, we can access the data like a normal JavaScript object.

JSON and APIs

JSON is commonly used with APIs.

For example:

fetch("https://dummyjson.com/products") .then((response) => response.json()) .then((data) => { console.log(data); }); 

Here:

  1. fetch() requests data from the API.
  2. response.json() reads and parses the JSON response.
  3. We can then use the data in JavaScript.

Important Points to Remember

  • JSON stands for JavaScript Object Notation.
  • JSON is used to store and exchange data.
  • JSON uses key-value pairs.
  • JSON.stringify() converts a JavaScript value into a JSON string.
  • JSON.parse() converts a JSON string into a JavaScript value.
  • JSON is commonly used when working with APIs.