Module 9 - JavaScript Object Notation (JSON)

Introducing JSON

What is JSON?

JSON (JavaScript Object Notation) is a lightweight format used to store and exchange data. It’s widely used in web development to transfer information between a server and a web client, such as when a web application needs to load or save data asynchronously without reloading the entire page. JSON is not only human-readable but also easy for computers to parse and generate, making it a universal data format.

What Does JSON Look Like?

JSON is structured in a way that resembles JavaScript objects, which is convenient for working with data in JavaScript. However, it has stricter syntax rules to ensure consistent formatting.

Basic Syntax Rules for JSON:

  • Data is presented in key-value pairs.
  • Keys must be strings enclosed in double quotes (""). Single quotes are not allowed for keys in JSON.
  • Values can be:
    • A string (enclosed in double quotes)
    • A number
    • An object (another set of key-value pairs, enclosed in curly braces {})
    • An array (a list of values, enclosed in square brackets [])
    • A boolean (true or false)
    • null (to represent an empty or non-existent value)
  • Data is separated by commas between key-value pairs.
  • Objects are enclosed in curly braces {}, and arrays are enclosed in square brackets [].

Comparison to JavaScript Objects

While JSON looks a lot like JavaScript objects, there are a few important differences:

  • Strings in JSON must use double quotes, whereas JavaScript objects can use either single or double quotes.
  • JSON does not allow functions, comments, or undefined values, all of which are permitted in JavaScript objects.
  • JSON keys must always be strings, but JavaScript object keys can be strings or identifiers.

Example of a Simple JSON Object

Here’s a basic example of a JSON object to illustrate the syntax:

{
        "name": "John",
        "age": 30,
        "isStudent": false,
        "skills": ["JavaScript", "HTML", "CSS"],
        "address": {
            "street": "123 Main St",
            "city": "Anytown",
            "zip": "12345"
        }
    }


Looking at the above example, here is a breakdown of some key features:

Key-Value Pairs: Each piece of data in the JSON object is presented as a key-value pair. For instance, "name": "John" pairs the key "name" with the value "John".

Data Types:

  • "name": A string value, "John", enclosed in double quotes.
  • "age": A number value, 30.
  • "isStudent": A boolean value, false, indicating that John is not a student.
  • "skills": An array of strings, ["JavaScript", "HTML", "CSS"], which lists John’s skills.
  • "address": A nested object that includes more key-value pairs related to John’s address.

Here is another example.  This time, the object represents a phone book with multiple records:

{
"phoneBook": [
{
"firstName": "John",
"lastName": "Doe",
"phone": "123-456-7890",
"email": "john.doe@example.com"
},
{
"firstName": "Jane",
"lastName": "Smith",
"phone": "987-654-3210",
"email": "jane.smith@example.com"
},
{
"firstName": "Michael",
"lastName": "Johnson",
"phone": "555-123-4567",
"email": "michael.johnson@example.com"
}
]
}


Valid Data Types in JSON

Understanding the valid data types that can be used in JSON is crucial for creating well-structured data:

Strings

Text enclosed in double quotes.

"example": "This is a string"

Numbers

Whole numbers or decimals (no quotes around numbers).

"price": 19.99

Objects

Collections of key-value pairs, enclosed in curly braces {}.

"user": {
"username": "jdoe",
"email": "jdoe@example.com"
}

Arrays

Lists of values, enclosed in square brackets []. The values can be any valid JSON data type.

"colors": ["red", "green", "blue"]

Booleans

true or false values.

"isAvailable": true

null

Represents an empty or non-existent value.

"middleName": null

Common Use Cases for JSON

JSON is used extensively in web applications, and understanding why it is so popular can help you appreciate its importance:

  1. Data Interchange: JSON is used to transfer data between a client (such as a web browser) and a server. For example, a web application might receive user data from a server in JSON format and display it on a webpage.
  2. APIs (Application Programming Interfaces): Most modern web APIs use JSON to format the data they send and receive. When you fetch data from an API, you are likely dealing with JSON.
  3. Configuration Files: JSON is often used in configuration files for applications, where settings need to be easily readable and modifiable.

Why JSON is So Popular

  • Human-Readable: JSON’s structure is simple and easy to understand, even for beginners.
  • Lightweight: JSON is compact, making it efficient to transfer over networks.
  • Language-Agnostic: JSON is not tied to JavaScript. It is supported by almost all modern programming languages, making it versatile for different software ecosystems.
  • Easy to Parse: JavaScript provides built-in methods for parsing JSON data, making it simple to work with in web applications.


Accessing JSON Data

The first step when working with JSON data is to understand how to access the information you need. In JavaScript, you can access data in a JSON object using dot notation or bracket notation.

Example JSON Object:

Here’s a simplified JSON object to illustrate the concepts

{
"firstName": "Alice",
"lastName": "Brown",
"email": "alice.brown@example.com",
"phone": "111-222-3333"
}

Accessing Values

Using dot notation:

let person = {
"firstName": "Alice",
"lastName": "Brown",
"email": "alice.brown@example.com",
"phone": "111-222-3333"
};

console.log(person.firstName); // Output: Alice
console.log(person.email); // Output: alice.brown@example.com

Using bracket notation:

console.log(person["lastName"]); // Output: Brown
console.log(person["phone"]); // Output: 111-222-3333

Both methods are useful, but dot notation is generally more readable and preferred unless the key name contains special characters or spaces.

Working with a JSON Dataset

When dealing with a dataset that contains multiple records, such as a JSON phone book, you will often use arrays to store each record. Here’s an example JSON phone book:

{
"phoneBook": [
{
"firstName": "John",
"lastName": "Doe",
"phone": "123-456-7890",
"email": "john.doe@example.com"
},
{
"firstName": "Jane",
"lastName": "Smith",
"phone": "987-654-3210",
"email": "jane.smith@example.com"
},
{
"firstName": "Michael",
"lastName": "Johnson",
"phone": "555-123-4567",
"email": "michael.johnson@example.com"
}
]
}

In JavaScript, you can access the data and loop through the records using a for loop.

Accessing Multiple Records Using a Loop

let phoneBook = {
"phoneBook": [
{
"firstName": "John",
"lastName": "Doe",
"phone": "123-456-7890",
"email": "john.doe@example.com"
},
{
"firstName": "Jane",
"lastName": "Smith",
"phone": "987-654-3210",
"email": "jane.smith@example.com"
},
{
"firstName": "Michael",
"lastName": "Johnson",
"phone": "555-123-4567",
"email": "michael.johnson@example.com"
}
]
};

// Loop through each record
phoneBook.phoneBook.forEach(record => {
console.log(`Name: ${record.firstName} ${record.lastName}`);
console.log(`Phone: ${record.phone}`);
console.log(`Email: ${record.email}`);
});


Modifying JSON Data

You can add, modify, or remove records from a JSON object in JavaScript. Let’s break down each operation.

Adding Records

To add a new record to a dataset that is an array of objects, use the push() method.

Example:

// Adding a new contact to the phone book
let newContact = {
"firstName": "Emily",
"lastName": "Clark",
"phone": "444-555-6666",
"email": "emily.clark@example.com"
};

phoneBook.phoneBook.push(newContact);

console.log(phoneBook.phoneBook);
// The new contact is now added to the phone book

Modifying Records

To modify an existing record, access the record by its index and update the necessary fields.

Example:

// Modifying the email address of the second contact
phoneBook.phoneBook[1].email = "jane.smith@newdomain.com";

console.log(phoneBook.phoneBook[1].email); // Output: jane.smith@newdomain.com

Removing Records

To remove a record from an array of objects, you can use the splice() method. The splice() method removes items from an array at a specified index.

Example:

// Removing the first contact from the phone book
phoneBook.phoneBook.splice(0, 1); // Removes 1 item at index 0

console.log(phoneBook.phoneBook);
// The first contact (John Doe) is now removed from the phone book


Methods for Working with JSON

JSON.parse()

Converts a JSON string into a JavaScript object. This is useful when you receive JSON data from an external source, such as a server or an API.

Example:

let jsonString = '{"name": "Anna", "age": 22}';
let jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // Output: Anna

JSON.stringify()

Converts a JavaScript object into a JSON string. This is helpful when you want to prepare your data to be sent to a server or saved in a file.

Example:

let jsObject = { name: "Anna", age: 22 };
let jsonString = JSON.stringify(jsObject);
console.log(jsonString); // Output: '{"name":"Anna","age":22}'

Looping Through JSON Objects: Use a for...in loop or forEach() method to iterate through all keys or all records.

Example Using for...in Loop:

let person = { "name": "Liam", "age": 28, "email": "liam@example.com" };

for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// Output:
// name: Liam
// age: 28
// email: liam@example.com

Videos for Module 9 - JavaScript Object Notation (JSON)

There are no videos yet this term for this Module. Check back soon!