JSON stands for JavaScript Object Notation. It is a lightweight, text-based data format that is commonly used to exchange data between a server and a web application.
One of the reasons why JSON is so popular in web development is because it is both machine-parseable and human-readable.
Since JSON is language-independent, you can easily send JSON data from a Java application to a Python application, or from a JavaScript application to a C# application.
JSON supports many data types including objects, arrays, strings, booleans, null, and numbers.
Here’s an example of a JSON object:
{
"name": "Alice",
"age": 30,
"isStudent": false,
"list of courses": ["Mathematics", "Physics", "Computer Science"]
}
As you can see, JSON uses key-value pairs to store information and each pair is separated by a comma. Each key must be wrapped in double quotes, otherwise you will get an error.
To access data from a JSON object, you can either use dot or bracket notation. In this example, we are using dot notation to access the age
from the JSON object:
import data from "./example.json" assert { type: "json" };
console.log(data.age);
This particular example is using what is known as an import
statement, which imports the JSON object into this file so we have access to it. You will learn more about the import
statement in a future lecture.
You can also use bracket notation to access information from JSON objects. Here is an example of accessing the list of courses
array:
import data from "./example.json" assert { type: "json" };
console.log(data["list of courses"]);
Using bracket notation is particularly useful here because the key contains multiple words separated by spaces. If we tried to use dot notation, it would result in an error.
In summary, JSON is a versatile format that can store many data types, including arrays and nested objects. By using dot notation or bracket notation, you can easily access the values stored within a JSON object.
How do JSON.parse() and JSON.stringify() work?