JSON in JavaScript

Introduction

In this article, we will cover JSON in JavaScript.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is primarily used to transmit data between a server and a web application, serving as a common language for exchanging data.

Structure of JSON


Objects

An object in JSON is represented by a set of key-value pairs enclosed in curly braces { }. Keys are always strings, and values can be of any valid JSON data type (string, number, boolean, null, object, array).

Example

{
  "name": "Vishal Yelve",
  "age": 33,
  "isEmployee": true
}

Arrays

An array in JSON is an ordered collection of values enclosed in square brackets [ ]. The values can be of any valid JSON data type, including objects or arrays themselves.

Example

[
  "Vishal",
  "Mahesh",
  "Deepak",
  "Bhaskar",
]

Nested Objects and Arrays

JSON allows nesting objects and arrays within each other to represent more complex data structures.

Example

{
   "name": "Vishal Yelve",
   "age": 33,
   "hobbies": ["Playing", "Blogging", "Coding"],
   "address": {
      "street": "123 Main St",
      "city": "Mumbai",
      "country": "India"
     }
}

JSON.parse() and JSON.stringify()

On the client-side, JavaScript provides built-in functions (JSON.parse() and JSON.stringify()) to convert JSON strings to JavaScript objects and vice versa, enabling seamless interaction with JSON data.

JSON.parse()

const jsonString = '{"name": "Vishal Yelve","age": 33, "isEmployee": true}';
const obj = JSON.parse(jsonString);

console.log(obj.name); // Output: Vishal Yelve
console.log(obj.age); // Output: 33
console.log(obj.isEmployee); // Output: true

JSON.parse()

In the example above, the JSON string jsonString is parsed using JSON.parse(), and the resulting JavaScript object obj can be accessed and manipulated like any other JavaScript object.

JSON.stringify()

JSON.stringify() is used to convert a JavaScript object into a JSON string.

const obj = {
   name: "Vishal Yelve",
   age: 33,
   isEmployee: true
};

const jsonString = JSON.stringify(obj);
console.log(jsonString);
// Output: {"name":"Vishal Yelve","age":33,"isEmployee":true

JSON.stringify()

In the example above, the JavaScript object obj is converted into a JSON string using JSON.stringify(), which can be stored, transmitted, or used as needed.

Summary

In this article, I have tried to cover JSON in Javascript.


Similar Articles