What is JSON in Javascript and how to work with JSON

## Introduction

JSON is short for JavaScript Object Notation is an lightweight format designed for easy data exchange. It supports every format of language and framework✌. JSON is pronounced as 'Jason'. Json is used for

  1. Storing Data
  2. Sharing data from client to server

The format of JSON is derived from Javascript Object Syntax, it is key-value data in the form of "key":"value" pairs. The file extension for storing JSON data is .json .

JSON Syntax

{ "firstName":"firstname", "lastName":"lastname" }

Q - Why there is need to change from JSON format to strings?

Ans - We need to change from JSON object to string because for transporting data to server because server understands strings not JSON.

Comparison with JavaScript Objects

JSON was developed to be used with any programming language. In terms of syntax JSON and JavaScript Objects are similar but in JavaScript objects keys are not in quotes (single or double) but in JSON both keys and values are in quotes both are strings.

Let us look at an example

JavaScript Objects Syntax

const person = { firstName:"Jhon", lastName:"Doe", age:17 }

JSON Syntax

const person = { "firstName":"Jhon", "lastName":"Doe", "age":7 }

JavaScript objects can work only in JavaScript but if we need data to be used in any language we can use JSON.

How to access JSON data?

JSON data can be accessed through JavaScript 'dot' ('.') notation like in above example we can access data by person.firstName which gives us 'Jhon' as result. We can also used Javascript square bracket syntax ([]) by writing person["firstName"].

When we are working with API's there also we get results in JSON format.

var user_profile = { "username" : "Sam", "social_media" : [ { "description" : "twitter", "link" : "twitter.com/sam" }, { "description" : "facebook", "link" : "facebook.com/sam" }, { "description" : "github", "link" : "github.com/sam } ] }

To access socia_media link for twitter of user we can write

user_profile.social_media[1].link which will gives us result as => twitter.com/sam

Functions in JSON

There are two function in JSON :-

  1. JSON.stringify()
  2. JSON.parse()

JSON.stringify() - We use this method when we want to send data from client to server in lightest way. This converts objects to strings.

var person = {"first_name" : "Sam", "last_name" : "Curan", "location" : "Australia"}

var s = JSON.stringify(person)

'{"first_name" : "Sam", "last_name" : "Curan", "location" : "Australia"}'

JSON.parse() - To convert strings to objects we use on client side we use JSON.parse().

var o = JSON.parse(person)