JSON Data Format & Serialization

🔗 REST API Lesson 5 Beginner

JSON (JavaScript Object Notation) is the de-facto data format for REST APIs. Understanding how to properly structure, validate, and serialize JSON data is critical for building interoperable, predictable APIs.

1 JSON Data Types
JSON — All Data Types
{
  "string":   "Hello, World!",
  "number":   42,
  "float":    3.14159,
  "boolean":  true,
  "nullValue": null,
  "array":    [1, "two", false, null],
  "object":   { "nested": "value" },
  "isoDate":  "2026-07-13T10:30:00Z",     // dates as ISO 8601 strings
  "currency": 1999,                        // store cents as integers
  "id":       "550e8400-e29b-41d4-a716"   // UUIDs as strings
}
2 JSON Naming Conventions
JSON — Naming Best Practices
// Use camelCase for all keys (not snake_case or PascalCase)
{
  "userId":      42,          // NOT: user_id or UserId
  "firstName":   "Balaji",    // NOT: first_name or FirstName
  "emailAddress":"b@ex.com",
  "createdAt":   "2026-01-01T00:00:00Z",
  "isActive":    true,        // booleans start with is/has/can
  "totalCount":  100,
  "itemsPerPage": 20
}

// Arrays use plural names
{
  "users": [...],
  "tags": ["nodejs", "rest"],
  "relatedProductIds": [1, 5, 7]
}
3 Parsing & Serializing JSON in Node.js
JavaScript — JSON Serialization
// Serialize object to JSON string
const user = { id: 1, name: "Balaji", createdAt: new Date() };
const jsonStr = JSON.stringify(user);
// Output: {"id":1,"name":"Balaji","createdAt":"2026-07-13T10:30:00.000Z"}

// Pretty print (for logging/debugging)
console.log(JSON.stringify(user, null, 2));

// Parse JSON string to object
const parsed = JSON.parse(jsonStr);
console.log(parsed.name); // Balaji

// Custom serialization — exclude sensitive fields
const sensitiveUser = { id: 1, name: "Balaji", passwordHash: "abc123" };
const safe = JSON.stringify(sensitiveUser, (key, val) => {
  if (key === "passwordHash") return undefined; // exclude
  return val;
});
// Output: {"id":1,"name":"Balaji"}

// Transform dates during serialization
const withDates = JSON.parse(jsonStr, (key, val) => {
  if (key === "createdAt") return new Date(val); // parse back to Date object
  return val;
});
4 Code Challenge
Challenge: Write a Node.js serializer function toPublicUser(userDoc) that transforms a MongoDB user document (with _id, passwordHash, __v) into a clean public-facing JSON object with camelCase keys and no sensitive fields.