Node.js Fundamentals

Learn Node.js from scratch including core concepts, modules, and basic server development.

beginner Backend Development 5 hours

Chapter 14: Working with JSON

Chapter 14 of 15

Chapter 14: Working with JSON

14.1 JSON Parsing

JSON (JavaScript Object Notation) is the standard format for data exchange. Node.js has built-in JSON support.

// Parse JSON string to object
const jsonString = '{"name":"John","age":30}';
const data = JSON.parse(jsonString);
console.log(data.name); // John

// Stringify object to JSON
const obj = { name: 'John', age: 30 };
const json = JSON.stringify(obj);
console.log(json); // {"name":"John","age":30}

JSON Methods:

  • JSON.parse(): Convert JSON string to JavaScript object
  • JSON.stringify(): Convert JavaScript object to JSON string

Error Handling:

try {
    const data = JSON.parse(invalidJson);
} catch (error) {
    console.error('Invalid JSON:', error.message);
}

// Safe parsing function
function safeParse(jsonString, defaultValue = null) {
    try {
        return JSON.parse(jsonString);
    } catch {
        return defaultValue;
    }
}

14.2 JSON in APIs

JSON is the standard format for REST APIs.

// Express JSON middleware
app.use(express.json());

// Receive JSON in request
app.post('/api/users', (req, res) => {
    const userData = req.body; // Already parsed JSON
    // Process userData
    res.json({ success: true, user: userData });
});

// Send JSON response
app.get('/api/users/:id', (req, res) => {
    const user = { id: 1, name: 'John', email: 'john@example.com' };
    res.json(user); // Automatically stringified
});

14.3 JSON File Operations

Read and write JSON files.

const fs = require('fs').promises;

// Read JSON file
async function readJsonFile(filePath) {
    try {
        const data = await fs.readFile(filePath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('Error reading JSON:', error);
        throw error;
    }
}

// Write JSON file
async function writeJsonFile(filePath, data) {
    try {
        const json = JSON.stringify(data, null, 2); // Pretty print
        await fs.writeFile(filePath, json, 'utf8');
    } catch (error) {
        console.error('Error writing JSON:', error);
        throw error;
    }
}

14.4 JSON Best Practices

Follow best practices when working with JSON.

  • Always handle parse errors
  • Validate JSON structure
  • Use pretty printing for readability (development)
  • Minify JSON for production (smaller size)
  • Be careful with circular references
  • Handle special values (undefined, functions) appropriately