Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

JSON Syntax in Node.js

Learn the syntax rules of JSON, including objects, key-value pairs, strings, numbers, booleans, null values, arrays, and nested objects. Understand valid and invalid JSON through detailed examples and practical Node.js programs.

1. What Is JSON Syntax?

JSON syntax defines the rules used to write structured data in JavaScript Object Notation format. JSON data is written as text and follows a specific structure so that applications can read and exchange it correctly.

JSON commonly uses objects, key-value pairs, arrays, and primitive values. To parse JSON successfully, the text must follow the JSON syntax rules.

Example

JSON
{
    "name": "Samadhan",
    "age": 22,
    "course": "Node.js",
    "isStudent": true
}

This JSON object contains four properties: name, age, course, and isStudent. Each property has a key and a corresponding value.

Definition: JSON syntax is the set of rules that determines how JSON data must be written so that it can be parsed correctly.

2. JSON Object Structure

A JSON object is enclosed in curly braces { }. Inside the object, properties are written as key-value pairs separated by commas.

A colon separates each key from its value. Property names must be strings enclosed in double quotation marks.

Example

JSON
{
    "name": "Pradnya",
    "city": "Pune",
    "marks": 90
}

In this example:

  • { } defines the beginning and end of the object.
  • "name", "city", and "marks" are property names.
  • The colon : separates a property name from its value.
  • Commas separate properties, except after the final property.

3. JSON Key-Value Pair Diagram

Every property in a JSON object contains a key and a value. The following example shows how a key-value pair is structured.

JSON Object

{ "name": "Samadhan" }

↓
Key

"name"

Identifies the property.

Value

"Samadhan"

Stores the property's data.

↓
Colon Separator

The colon connects the key and its value.

4. Rule 1: Use Double Quotes

JSON requires double quotation marks around property names and string values. Single quotes and unquoted property names are not valid JSON syntax.

Valid JSON

JSON
{
    "name": "Samadhan",
    "course": "Node.js"
}

Invalid JSON

Invalid JSON
{
    name: 'Samadhan',
    course: 'Node.js'
}

Explanation: The invalid example uses unquoted keys and single-quoted strings. These are allowed in some JavaScript contexts, but they are not valid JSON syntax.

5. Rule 2: Use a Colon Between Key and Value

A colon separates each JSON property name from its value. Without the colon, the property is not written correctly.

Valid JSON

JSON
{
    "age": 22
}

Invalid JSON

Invalid JSON
{
    "age" 22
}

The invalid example is missing the colon between the key "age" and its value 22.

6. Rule 3: Separate Properties with Commas

When a JSON object contains multiple properties, a comma separates one property from the next. Do not add a comma after the last property.

Valid JSON

JSON
{
    "name": "Samadhan",
    "age": 22,
    "city": "Pune"
}

Invalid JSON: Trailing Comma

Invalid JSON
{
    "name": "Samadhan",
    "age": 22,
}

The comma after 22 is a trailing comma because no property follows it. Standard JSON does not allow it.

7. Rule 4: JSON Data Types

JSON supports strings, numbers, booleans, null, objects, and arrays. Each type represents a different kind of value.

Data Type Example Meaning
String "name": "Pradnya" Represents text.
Number "marks": 85 Represents a numeric value.
Boolean "isActive": true Represents true or false.
Null "middleName": null Represents an empty or absent value.
Object "address": { "city": "Pune" } Contains key-value pairs.
Array "skills": ["JS", "Node.js"] Contains an ordered collection of values.

Complete Example

JSON
{
    "name": "Pradnya",
    "age": 22,
    "marks": 85.5,
    "isActive": true,
    "middleName": null,
    "address": {
        "city": "Pune",
        "state": "Maharashtra"
    },
    "skills": [
        "JavaScript",
        "Node.js"
    ]
}

8. Rule 5: JSON Arrays

A JSON array is an ordered collection of values enclosed in square brackets [ ]. Array values are separated by commas.

Example

JSON
{
    "name": "Samadhan",
    "skills": [
        "JavaScript",
        "Node.js",
        "SQL"
    ]
}

The skills property contains an array with three string values. Arrays can also contain numbers, booleans, objects, and other valid JSON values.

Example: Array of Numbers

JSON
{
    "marks": [75, 80, 85, 90]
}

9. Rule 6: Nested JSON Objects

A JSON object can contain another object as a property value. This is called a nested object. It helps represent related information in a structured way.

Example

JSON
{
    "name": "Samadhan",
    "course": "Node.js",
    "address": {
        "city": "Pune",
        "state": "Maharashtra",
        "pinCode": 411001
    }
}

The address property contains another object with city, state, and pinCode properties. Nested objects are useful when information belongs to a related category.

10. JSON Structure Diagram

A JSON document can contain an object with simple properties, nested objects, and arrays.

Student JSON Object

{ ... }

Simple Properties

"name": "Samadhan"
"marks": 85

Nested Object

"address": { ... }
City and state details

Array Property

"skills": ["JavaScript", "Node.js"]

11. Validate JSON Using Node.js

Node.js can check whether a JSON string follows valid JSON syntax by attempting to parse it using JSON.parse(). If the input is invalid, the method throws a syntax error.

Complete Program

JavaScript - app.js
const jsonText = `{
    "name": "Samadhan",
    "course": "Node.js",
    "marks": 85
}`;

try {
    const student = JSON.parse(jsonText);

    console.log("Valid JSON");
    console.log("Student Name:", student.name);
    console.log("Course:", student.course);
    console.log("Marks:", student.marks);
} catch (error) {
    console.log("Invalid JSON");
}

Output

Output
Valid JSON
Student Name: Samadhan
Course: Node.js
Marks: 85

Explanation:

  • jsonText stores JSON-formatted text.
  • JSON.parse(jsonText) parses the text into a JavaScript object.
  • The program displays the properties after successful parsing.
  • If parsing fails, execution moves to the catch block.

12. Valid and Invalid JSON Comparison

Invalid Syntax Correct JSON Syntax
{ name: "Samadhan" } { "name": "Samadhan" }
{ "name": 'Samadhan' } { "name": "Samadhan" }
{ "age" 22 } { "age": 22 }
{ "age": 22, } { "age": 22 }
{ "active": undefined } { "active": null }

JSON does not support JavaScript's undefined value. Use null when the JSON data needs to represent an explicitly empty value.

13. Common JSON Syntax Mistakes

  • Forgetting double quotes around property names.
  • Using single quotes for JSON strings.
  • Forgetting the colon between a key and its value.
  • Forgetting commas between properties.
  • Adding a comma after the last property or array element.
  • Using comments inside a JSON document.
  • Using JavaScript-only values such as undefined.
Tip: When JSON parsing fails, inspect the error and check the quotation marks, commas, colons, braces, and brackets.

14. Practice Tasks

Task 1: Create Employee JSON

Create a JSON object containing employee ID, employee name, department, salary, and active status.

Use a number for the ID and salary, strings for text, and a boolean for active status.

Task 2: Create an Array of Skills

Create a JSON object containing a student's name and an array of at least three skills. Ensure all strings use double quotation marks.

Task 3: Find and Correct Errors

Correct the following invalid JSON:

Invalid JSON
{
    name: 'Pradnya',
    "age": 22,
    "isStudent": true,
}

Correct the property name, string quotes, and trailing comma.

Important Points

  • JSON objects use curly braces { }.
  • JSON arrays use square brackets [ ].
  • Property names and string values require double quotes.
  • Colons separate keys and values; commas separate properties.
  • JSON supports strings, numbers, booleans, null, objects, and arrays.
  • JSON does not allow comments or trailing commas.
  • JSON.parse() can be used to validate JSON syntax by attempting to parse the text.
  • JavaScript object literals and JSON text are different formats and follow different syntax rules.

Summary

JSON syntax defines how structured data must be written using objects, key-value pairs, arrays, and supported data types. JSON property names and string values must use double quotation marks, colons separate keys from values, and commas separate properties. JSON supports strings, numbers, booleans, null, objects, and arrays, but does not allow comments, trailing commas, or JavaScript-only values such as undefined. In Node.js, JSON.parse() can parse valid JSON text and help identify syntax errors. Following JSON syntax rules makes data easier to exchange and process reliably.