JSON Introduction in Node.js
Learn what JSON is, why it is used, how JSON represents data, and how Node.js applications work with JSON objects and files. Understand JSON syntax, data types, practical examples, and the difference between JavaScript objects and JSON strings.
1. What Is JSON?
JSON stands for JavaScript Object Notation. It is a text-based data format used to store and exchange structured data between applications.
JSON represents information using key-value pairs and arrays. It is commonly used when applications send data to a server, receive data from an API, or store structured information in a text file.
For example, a student record can contain a student's name, course, and marks. JSON provides a structured way to represent this information.
Example: Student Data in JSON
{
"name": "Samadhan",
"course": "Node.js",
"marks": 85
}
In this example, name, course, and
marks are keys. Their corresponding values are
"Samadhan", "Node.js", and
85.
2. Why Do We Use JSON?
Applications often need to exchange information in a format that is easy to read and process. JSON is useful because it represents structured data in a compact text format.
- Data Exchange: Applications can send and receive structured information.
- API Communication: Web APIs commonly use JSON request and response bodies.
- Data Storage: JSON can store structured information in text files.
- Readable Structure: Keys and values make data easier to understand.
- Nested Data: Objects and arrays can represent related information.
- Language Support: Many programming languages can read and generate JSON.
3. How JSON Works in an Application
An application can convert structured data into a JSON string before sending or storing it. Another part of the application can parse that JSON string back into a usable data structure.
Step 1: Application Data
Example: a JavaScript object containing student details.
Step 2: Convert to JSON
Use JSON.stringify() to create a JSON string.
Step 3: Send or Store
Transfer the JSON text or save it in a file.
Step 4: Parse JSON
Use JSON.parse() to convert valid JSON text
into a JavaScript value.
4. JSON Syntax Rules
JSON follows specific syntax rules. A JSON document must follow these rules to be parsed successfully.
- JSON object keys must be enclosed in double quotation marks.
- String values must use double quotation marks.
-
Key-value pairs are separated using a colon
(
:). - Multiple properties are separated using commas.
-
Objects use curly braces
{ }. -
Arrays use square brackets
[ ]. - JSON supports strings, numbers, booleans, null, objects, and arrays.
- JSON does not support comments or trailing commas.
Valid JSON Example
{
"name": "Pradnya",
"age": 22,
"isStudent": true,
"city": "Pune"
}
Invalid JSON Example
{
name: 'Pradnya',
age: 22,
}
The invalid example uses an unquoted key, single quotes for a string, and a trailing comma. These do not follow JSON syntax.
5. JSON Data Types
JSON supports several data types. Choosing the correct type helps represent information accurately.
| Data Type | Example | Description |
|---|---|---|
| String | "name": "Samadhan" |
Represents text enclosed in double quotes. |
| Number | "marks": 85 |
Represents an integer or decimal number. |
| Boolean | "isActive": true |
Represents either true or false. |
| Null | "middleName": null |
Represents an intentionally empty value. |
| Object | "address": { "city": "Pune" } |
Represents a collection of key-value pairs. |
| Array | "skills": ["JavaScript", "Node.js"] |
Represents an ordered collection of values. |
Complete JSON Example
{
"name": "Samadhan",
"age": 22,
"marks": 85.5,
"isStudent": true,
"middleName": null,
"address": {
"city": "Pune",
"state": "Maharashtra"
},
"skills": [
"JavaScript",
"Node.js",
"SQL"
]
}
This example combines strings, numbers, a boolean, null, a nested object, and an array in one JSON document.
6. JSON vs JavaScript Object
JSON and JavaScript objects look similar, but they serve different purposes. A JavaScript object is a runtime value that a program can work with directly. JSON is a text format used to represent data.
JavaScript Object
const student = {
name: "Samadhan",
marks: 85
};
console.log(student.name);
Output
Samadhan
Equivalent JSON Text
{
"name": "Samadhan",
"marks": 85
}
Notice that JSON requires double quotes around property names and string values. A JavaScript object can be used directly by JavaScript code, while JSON text must be parsed before accessing its data as an object.
7. Using JSON in Node.js
Node.js includes the global JSON object.
Its two commonly used methods are JSON.stringify()
and JSON.parse().
- JSON.stringify(): Converts a JavaScript value into a JSON string.
- JSON.parse(): Parses valid JSON text and returns the corresponding JavaScript value.
JSON.stringify() or JSON.parse().
They are available through JavaScript's built-in JSON object.
8. Practical Program: Create and Display JSON Data
Let us create a JavaScript object containing student details and display its properties in the terminal.
Complete Program
const student = {
name: "Samadhan",
course: "Node.js",
marks: 85
};
console.log("Student Name:", student.name);
console.log("Course:", student.course);
console.log("Marks:", student.marks);
Output
Student Name: Samadhan
Course: Node.js
Marks: 85
Explanation:
The student variable stores a JavaScript object.
Dot notation accesses individual properties such as
student.name and student.marks.
9. JSON Conversion Flow
The following diagram explains the conversion between JavaScript values and JSON text.
JavaScript Object
{ name: "Samadhan", marks: 85 }
JSON.stringify()
Converts the object into JSON text.
JSON String
{"name":"Samadhan","marks":85}
JSON.parse()
Converts valid JSON text back into a JavaScript value.
10. How to Run the Program
-
Create a folder named
JSONExample. -
Create a JavaScript file named
app.js. - Write the student object program in that file.
- Open a terminal in the project folder.
- Run the file using the Node.js command.
Terminal Command
node app.js
Node.js executes the JavaScript file and prints the student details in the terminal.
11. Common JSON Mistakes
| Mistake | Correct Approach |
|---|---|
| Using single quotes for JSON strings. | Use double quotes for JSON string values. |
| Leaving object property names unquoted. | Enclose JSON property names in double quotes. |
| Adding a trailing comma. | Remove the comma after the final property or array element. |
| Using comments inside JSON. | Keep comments outside the JSON document. |
| Parsing invalid JSON text. | Ensure the text follows JSON syntax before parsing. |
| Confusing a JavaScript object with a JSON string. | Use JSON.stringify() and JSON.parse() when conversion is needed. |
12. Practice Tasks
Task 1: Create Employee JSON Data
Create a JavaScript object containing employee ID, name, department, and salary. Display each property in the terminal.
Task 2: Create Product JSON Data
Create a product object with product name, price, availability, and category. Use appropriate data types for each property.
Task 3: Work with Nested JSON Data
Create a student object containing a nested address object and an array of skills. Display the student's city and the first skill in the terminal.
Important Points
- JSON stands for JavaScript Object Notation.
- JSON is a text format used to represent structured data.
- JSON keys and string values require double quotes.
- JSON supports strings, numbers, booleans, null, objects, and arrays.
- JSON does not support comments or trailing commas.
-
JSON.stringify()converts a JavaScript value into a JSON string. -
JSON.parse()parses valid JSON text into a JavaScript value. - JSON is commonly used for API communication and structured data storage.
Summary
JSON stands for JavaScript Object Notation and is a text-based format used to represent and exchange structured data. It supports strings, numbers, booleans, null, objects, and arrays. JSON follows strict syntax rules, including double-quoted property names and string values, and does not allow comments or trailing commas. In Node.js, JSON.stringify() converts JavaScript values into JSON text, while JSON.parse() converts valid JSON text back into JavaScript values. JSON is widely used for API communication, data exchange, and structured storage.