Labs ICT
โญ Pro Login

JSON Handling

Parse and stringify JSON data.

2 min read | Node.js Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

JSON Handling

JSON (JavaScript Object Notation) is the standard for data exchange on the web. Node.js has built-in support for parsing and generating JSON.

Parsing JSON

const jsonString = '{"name": "Alice", "age": 30}';

// Parse JSON string to object
const user = JSON.parse(jsonString);
console.log(user.name);  // Alice

// Safe parsing with error handling
try {
  const data = JSON.parse(input);
} catch (err) {
  console.error("Invalid JSON:", err.message);
}

Stringifying JSON

const user = { name: "Alice", age: 30 };

// Convert object to JSON string
const json = JSON.stringify(user);
// '{"name":"Alice","age":30}'

// Pretty print with indentation
const pretty = JSON.stringify(user, null, 2);
// {
//   "name": "Alice",
//   "age": 30
// }

Reading and Writing JSON Files

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

// Read JSON file
async function readJSON(filename) {
  const data = await fs.readFile(filename, "utf-8");
  return JSON.parse(data);
}

// Write JSON file
async function writeJSON(filename, data) {
  await fs.writeFile(filename, JSON.stringify(data, null, 2));
}

Replacer and Reviver

// Replacer: filter/transform during stringify
const filtered = JSON.stringify(user, (key, value) => {
  if (key === "password") return undefined;  // Exclude
  return value;
});

// Reviver: transform during parse
const parsed = JSON.parse(jsonString, (key, value) => {
  if (key === "date") return new Date(value);
  return value;
});

๐Ÿงช Quick Quiz

Which method converts JSON string to object?