</>
Skip to content
Node.js lessons (31/44)

Node.js — JSON

Parse JSON

const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // 'John'

Stringify JSON

const obj = { name: 'John', age: 30 };
const jsonString = JSON.stringify(obj);
// '{"name":"John","age":30}'

Pretty Print

const pretty = JSON.stringify(obj, null, 2);

Custom Replacer

const filtered = JSON.stringify(obj, (key, value) => {
    if (key === 'password') return undefined;
    return value;
});

Reading JSON Files

const fs = require('fs');

// Synchronous
const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));

// Asynchronous
const data = JSON.parse(await fs.promises.readFile('data.json', 'utf8'));

Writing JSON Files

const data = { users: [{ name: 'John' }] };
await fs.promises.writeFile('data.json', JSON.stringify(data, null, 2));

Mini Practice

  1. Parse JSON strings
  2. Stringify objects
  3. Read/write JSON files
  4. Use custom replacer

Up Next

Continue with REST API — building REST APIs.

Related Topics

Frequently Asked Questions about JSON

What is JSON in Node.js?

JSON is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn JSON?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn JSON.

Why is JSON important in Node.js?

JSON is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.