Introduction
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is easy for humans to read and write, and for machines to parse and generate. JSON is language-independent, but it uses conventions familiar to programmers of the C-family of languages, including JavaScript. It is essentially a text-based format that represents data in a structured and organized manner.
Conceptualizing JSON
To conceptualize JSON in real-world terms, imagine JSON as a digital form used to collect information. For example, when filling out a form to gather student details such as name, gender, address, phone number, and email address, each field corresponds to a key-value pair in a JSON object.
Here is a Form Example
Name: John Doe
Age: 30
Address:
Street: 123 Main St
City: New York
ZIP: 10001
Hobbies:
[ ] Reading
[ ] Coding
[X] Cycling
[X] Hiking
Middle Name:
Secondary Email:
And here is the JSON equivalent:
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
},
"hobbies": ["Cycling", "Hiking"],
"middleName": null,
"secondaryEmail": null
}
Note the type of data in each form field and compare it with its equivalent in the JSON object. For instance, the address field in the form is a section and is represented as an object in JSON. The hobbies field, which is a multiple-choice field on the form, is represented as an array in JSON. The middlename which is an empty field in the form is represented as null in the JSON object.
JSON Methods
We will now look at serialization and deserialization of data by using the JSON.stringify()
and JSON.parse()
methods.
Serialization in JavaScript
- Function:
JSON.stringify()
- Usage: Converts a JavaScript object into a JSON string.
- Example:
javascript const person = { name: 'Ola Nordmann', age: 30, isDeveloper: true }; const jsonString = JSON.stringify(person); // logs: '{"name":"Ola Nordmann","age":30,"isDeveloper":true}'
Deserialization in JavaScript
- Function:
JSON.parse()
- Usage: Parses a JSON string, constructing the JavaScript value or object described by the string.
- Example:
javascript const jsonString = '{"name": "Ola Nordmann", "age": 30, "isDeveloper": true}'; const person = JSON.parse(jsonString); // logs: { name: 'Ola Nordmann', age: 30, isDeveloper: true }
JSON Data Types
JSON is able to parse multiple data types, however we cannot parse functions or undefined values.
Key Concepts of JSON
- Syntax: Resembles JavaScript object literal syntax, but with some differences (e.g., property names must be in double quotes).
- Data Types: JSON supports strings, numbers, objects, arrays, booleans, and null.
- Serialization and Deserialization: Converting JavaScript objects to JSON strings (serialization) and parsing JSON strings back to JavaScript objects (deserialization).
Why JSON is Important in JavaScript
- Data Exchange: JSON is widely used in web applications for sending data between a server and a client.
- Configuration: Many JavaScript tools and frameworks use JSON files for configuration (e.g.,
package.json
in Node.js projects). - Storage: JSON is used to store data in a structured way, such as in localStorage, sessionStorage and databases like MongoDB.
Dealing with JSON Objects
Dealing with a JSON (JavaScript Object Notation) object in JavaScript involves several key operations such as parsing JSON from strings, accessing, updating, and deleting values within the JSON object, and converting JavaScript objects back into JSON format. Here’s a guide to working with JSON effectively.
Parsing JSON from a String
If you receive JSON as a string (for example, from a server or API), you’ll need to convert it into a JavaScript object using JSON.parse(). You can confirm the data type of JSON received using typeof()
method.
let jsonString = '{"name": "John", "age": 30, "city": "New York"}';
let obj = jsonString;
// checks if jsonString is of string data type and parse is to object
if (typeof(jsonString) === 'string') {
obj = JSON.parse(jsonString);
}
console.log(obj.name); // Output: John
console.log(obj.age); // Output: 30
Accessing Values in a JSON Object
Once you have a JSON object, you can access its properties using dot notation or bracket notation.
let person = {
"name": "John",
"age": 30,
"city": "New York"
};
// Dot notation
console.log(person.name); // Output: John
// Bracket notation
console.log(person['city']); // Output: New York
Updating Values in a JSON Object
You can update values in the JSON object by directly assigning new values using dot or bracket notation.
person.age = 35; // Update age
person['city'] = 'San Francisco'; // Update city
console.log(person);
// Output: {name: "John", age: 35, city: "San Francisco"}
Adding New Properties
You can add new properties to a JSON object by simply assigning a new key and value.
person.country = "USA"; // Add new key-value pair
console.log(person);
// Output: {name: "John", age: 35, city: "San Francisco", country: "USA"}
Deleting Properties from a JSON Object
To delete a property from a JSON object, use the delete operator.
delete person.city; // Remove city
console.log(person);
// Output: {name: "John", age: 35, country: "USA"}
Conclusion
Understanding JSON is crucial for JavaScript developers when handling data in web applications. Its simplicity and effectiveness in data representation make it an indispensable tool in modern web development. JSON is structured as an object, and working with it is similar to working with any other JavaScript object you may have encountered.
Lesson Task
Brief
You will practice converting a JavaScript object to a JSON string and back again.
Task: Practice with JSON
- Create a JSON String:
Define a JavaScript object representing a book with properties for:
- title
- author
- publication year.
Convert the object to JSON and console.log
the value.
- Parse a JSON String:
Convert the book string back to an object and console.log
the value.
Solution:
- Create a JSON String:
// Create a JavaScript object representing a book
const book = {
title: 'Hunger',
author: 'Knut Hamsun',
publicationYear: 1890
};
// Convert the object to JSON
const jsonString = JSON.stringify(book);
// Log the JSON string
console.log(jsonString);
// logs: {"title":"Hunger","author":"Knut Hamsun","publicationYear":1890}
- Parse a JSON String:
// Create a JSON string representing a book
const jsonString = '{"title":"Hunger","author":"Knut Hamsun","publicationYear":1890}';
// Convert the JSON string to an object
const book = JSON.parse(jsonString);
// Log the object
console.log(book);
// logs: { title: 'Hunger', author: 'Knut Hamsun', publicationYear: 1890 }