Working with JSON Data

πŸ“˜ Node.js πŸ‘ 54 views πŸ“… Nov 05, 2025
⏱ Estimated reading time: 2 min

JSON (JavaScript Object Notation) is a lightweight data format used to store and exchange data between a client and a server.
It is the most common format for APIs and web services.


1. What Is JSON?

JSON represents data as:

  • Key–value pairs

  • Arrays and objects

  • Text-based and language-independent format

Example:

{ "name": "Alice", "age": 25, "skills": ["Node.js", "Express"] }

2. JSON vs JavaScript Objects

JSONJavaScript Object
Data formatProgramming object
Uses double quotesQuotes optional
No functionsCan contain functions

3. Parsing and Stringifying JSON

Convert JSON β†’ JavaScript Object

const obj = JSON.parse('{"name":"Bob"}');

Convert JavaScript Object β†’ JSON

const json = JSON.stringify({ name: 'Bob' });

4. Working with JSON in Node.js

Reading JSON from a File

const fs = require('fs'); const data = fs.readFileSync('data.json', 'utf8'); const users = JSON.parse(data);

Writing JSON to a File

const fs = require('fs'); const users = [{ name: 'John', age: 30 }]; fs.writeFileSync('users.json', JSON.stringify(users, null, 2));

βœ” null, 2 formats JSON neatly


5. Sending JSON in Express.js

Sending JSON Response

app.get('/user', (req, res) => { res.json({ name: 'Alice', age: 25 }); });

Receiving JSON Data

app.use(express.json()); app.post('/user', (req, res) => { console.log(req.body); res.send('Data received'); });

6. Handling JSON APIs

Typical API flow:

  1. Client sends JSON request

  2. Server parses JSON body

  3. Server processes data

  4. Server responds with JSON


7. Common JSON Operations

  • Read data

  • Update fields

  • Add new entries

  • Delete entries

Example:

users.push({ name: 'Sam', age: 28 });

8. Error Handling with JSON

try { JSON.parse(invalidData); } catch (err) { console.error('Invalid JSON'); }

9. Best Practices

  • Always validate incoming JSON

  • Use res.json() instead of res.send()

  • Format JSON for readability

  • Handle parsing errors properly


10. Real-World Use Cases

  • REST APIs

  • Configuration files

  • Data exchange between services

  • Frontend–backend communication


11. Summary

  • JSON is the standard data format for web apps

  • Easily parsed and generated in Node.js

  • Express provides built-in JSON handling

  • Essential for API development


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes