Lecture Notes for Day 13: JSON in JavaScript

Rashmi Mishra
0

Lecture Notes for Day 13

JSON in JavaScript


Objective:

To understand JSON (JavaScript Object Notation), its syntax, and how to work with JSON data in JavaScript, including converting between JavaScript objects and JSON format.


Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format that's easy to read and write for humans and easy to parse and generate for machines. JSON is commonly used to transmit data between a server and a client.

Key Characteristics of JSON:

  • It is text-based and is language-independent, though it is often used with JavaScript.
  • JSON is commonly used in web development to send and receive data from a server.
  • JSON format is easy to understand and read by both humans and computers.

1. JSON Syntax

JSON data is represented as key-value pairs. The syntax is similar to JavaScript object literals, but with a few key rules:

Basic Syntax Rules:

1.  Data is organized in key-value pairs: Each key is followed by a colon and a value.

2.  Keys must be strings in double quotes: Unlike JavaScript objects, JSON keys are always in double quotes ("").

3.  Values can be different data types:

o    String (must be in double quotes)

o    Number (integer or decimal, without quotes)

o    Boolean (true or false, without quotes)

o    Array (ordered list of values)

o    Object (nested structure)

o    Null (special value representing no data)

Example of JSON Data:

Here’s a JSON object containing details about a student: 

{

  "name": "John Doe",

  "age": 21,

  "isStudent": true,

  "subjects": ["Math", "Physics", "Chemistry"],

  "address": {

    "street": "123 Main St",

    "city": "New York",

    "zip": "10001"

  }

}

In this example:

  • "name" is a string.
  • "age" is a number.
  • "isStudent" is a boolean.
  • "subjects" is an array of strings.
  • "address" is an object containing another set of key-value pairs.

2. JSON in JavaScript: 

Converting JavaScript Objects to JSON and Vice Versa

When working with JSON in JavaScript, you’ll often need to convert data from a JavaScript object to JSON format and vice versa.

JSON.stringify(): Converting JavaScript Objects to JSON

JSON.stringify() is a method that converts a JavaScript object into a JSON string. This is useful when you need to send data to a server or store data in a format that can be easily parsed by other applications.

Syntax:

JSON.stringify(value);

Example:

Suppose we have a JavaScript object and want to convert it to JSON format:

const student = {

  name: "Jane Smith",

  age: 22,

  isStudent: true,

  subjects: ["Biology", "Chemistry", "Physics"]

}; 

const jsonString = JSON.stringify(student);

console.log(jsonString); 

 Output:

{"name":"Jane Smith","age":22,"isStudent":true,"subjects":["Biology","Chemistry","Physics"]}

Here, JSON.stringify() has converted the student JavaScript object into a JSON string that can now be sent to a server or stored in local storage.

Additional Options with JSON.stringify():

  • Formatting: Adding indentation for readability:

JSON.stringify(student, null, 2);

  • Filtering Properties: Only include specific properties by providing an array of keys:

JSON.stringify(student, ["name", "age"]);


JSON.parse(): Converting JSON to JavaScript Objects

JSON.parse() is a method that converts a JSON string back into a JavaScript object. This is useful for retrieving data received from a server, which is typically in JSON format.

Syntax:

JSON.parse(text);

Example:

Suppose we receive a JSON string from a server and want to convert it back to a JavaScript object:


const jsonString = '{"name":"Jane Smith","age":22,"isStudent":true,"subjects":["Biology","Chemistry","Physics"]}'; 

const studentObject = JSON.parse(jsonString);

console.log(studentObject);

 

 

Output:

{

  name: "Jane Smith",

  age: 22,

  isStudent: true,

  subjects: ["Biology", "Chemistry", "Physics"]

}

Here, JSON.parse() converts the JSON string back into a JavaScript object, allowing us to work with the data as an object in JavaScript.


Key Use Cases for JSON in JavaScript

  • Data Exchange: JSON is widely used to send data from a server to a web page.
  • Storing Data: JSON can be stored as text files or in local storage for persistent data.
  • Configuration Files: Many applications and services use JSON files for configuration (for example, package.json in Node.js).

Summary:

  • JSON is a format for structuring data that is easy to read and write.
  • JSON.stringify() is used to convert JavaScript objects to JSON format.
  • JSON.parse() is used to parse JSON strings and convert them back to JavaScript objects.

Exercise

1.  Create a JavaScript object representing a book (title, author, yearPublished, genre) and convert it to JSON format.

2.  Write a JSON string representing a movie (title, director, releaseYear, genres) and convert it to a JavaScript object.


Additional Resources:


 

Post a Comment

0Comments

Post a Comment (0)