MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
JSON.stringify Replacer & JSON.parse Reviver0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
12.1JSON.stringify Replacer & JSON.parse Reviver12.2Circular Reference Handling & Custom Serialization12.3JSON Schema Validation12.4Streaming JSON & NDJSON
HomeTutorialsJavaScript for AdvancedJSON.stringify Replacer & JSON.parse Reviver
Circular Reference Handling & Custom Serialization

JSON.stringify Replacer & JSON.parse Reviver

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Almost every JavaScript developer uses JSON.stringify(data) and JSON.parse(str). However, few realize that both methods accept a powerful second argument: the Replacer and the Reviver. These transform functions enable masking sensitive fields, formatting custom types, and restoring Date and Map instances during serialization.


1. JSON.stringify() with the Replacer

The syntax for JSON.stringify:

1JSON.stringify(value, replacer, space);

Option A: Replacer as a Function (Filter / Transformer)

The replacer function is called for every key-value pair. Returning undefined omits the property from the output:

1const userProfile = {
2 id: 101,
3 username: 'alex_admin',
4 passwordHash: '$2b$10$e892u3...', // SENSITIVE!
5 creditCard: '4111-2222-3333-4444', // SENSITIVE!
6 createdAt: new Date()
7};
8 
9// Mask sensitive fields during serialization:
10const safeJson = JSON.stringify(userProfile, (key, value) => {
11 if (key === 'passwordHash') return undefined; // Strips key completely!
12 if (key === 'creditCard') return '****-****-****-' + value.slice(-4); // Masks
13 return value; // Passthrough other values
14}, 2);
15 
16console.log(safeJson);
17// {
18// "id": 101,
19// "username": "alex_admin",
20// "creditCard": "****-****-****-4444",
21// "createdAt": "2026-03-15T..."
22// }

Option B: Replacer as an Array (Property Whitelist)

Passing an array of property names acts as an exact whitelist:

1// Include ONLY 'id' and 'username'
2const whitelistedJson = JSON.stringify(userProfile, ['id', 'username']);
3console.log(whitelistedJson); // '{"id":101,"username":"alex_admin"}'

2. JSON.parse() with the Reviver

By default, JSON.parse() converts ISO date strings into plain strings. A Reviver function inspects each key-value pair and transforms it back into a native JavaScript object:

1const jsonString = '{"eventId":"EV-99","scheduledDate":"2026-06-15T09:30:00.000Z"}';
2 
3// Reviver: Restore ISO string into a true Date instance!
4const parsedEvent = JSON.parse(jsonString, (key, value) => {
5 // Check if string matches ISO 8601 date pattern
6 if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
7 return new Date(value);
8 }
9 return value;
10});
11 
12console.log(parsedEvent.scheduledDate instanceof Date); // TRUE!
13console.log(parsedEvent.scheduledDate.getFullYear()); // 2026

3. Serializing BigInt and Custom Types

By default, attempting to serialize a BigInt throws TypeError: Do not know how to serialize a BigInt. A replacer handles this cleanly:

1const transaction = {
2 id: 'TX-1',
3 amountSatoshis: 1000000000000000000n // BigInt!
4};
5 
6const json = JSON.stringify(transaction, (key, val) =>
7 typeof val === 'bigint' ? val.toString() + 'n' : val
8);
9 
10console.log(json); // '{"id":"TX-1","amountSatoshis":"1000000000000000000n"}'

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What happens if a JSON.stringify() replacer function returns undefined for a given property key?
Question 2
How can you whitelist only the properties "id" and "title" when calling JSON.stringify(book)?
Question 3
What is the primary role of the reviver function in JSON.parse(str, reviver)?
Question 4
Why does JSON.stringify({ amount: 100n }) throw an error without a replacer?
Question 5
What does the third parameter in JSON.stringify(obj, null, 2) control?
Next Lesson

Circular Reference Handling & Custom Serialization

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
GraphQL Queries, Mutations & SubscriptionsCircular Reference Handling & Custom Serialization

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext