JavaScript JSON: parse, stringify, Files and Deep Copy with structuredClone
JSON (JavaScript Object Notation) is the language that APIs, configuration files and test data speak. Every REST response you check, every package.json and every data-driven test file is JSON. In this lesson you will learn the JSON rules, convert between JSON text and JavaScript objects with JSON.parse and JSON.stringify, control the output with replacers, revivers and indentation, read and write JSON files in Node.js, handle the errors you will meet, and make deep copies safely.
📖 What You’ll Learn: JSON syntax and how it differs from JavaScript objects, JSON.stringify with indentation, replacer and toJSON, what stringify drops or changes (undefined, functions, dates, NaN, BigInt), JSON.parse with a reviver, parse errors, circular references, reading and writing JSON files with fs, deep copying with JSON versus structuredClone, and comparing API responses.
📄 What Is JSON?
Definition: JSON is a text format for structured data. It looks like JavaScript object and array literals, but it is just a string with stricter rules. Almost every programming language can read and write it.
📄 user.json
{
"id": 7,
"name": "Asha Rao",
"active": true,
"roles": ["tester", "admin"],
"manager": null,
"address": { "city": "Pune", "pin": "411001" }
}
| JSON rule | JavaScript object literal |
|---|---|
| Keys must be in double quotes | Quotes are optional |
| Strings must use double quotes | Single, double or back-ticks |
| No trailing commas | Trailing commas allowed |
| No comments | Comments allowed |
| Values: string, number, boolean, null, object, array | Also undefined, functions, Date, Map, NaN, BigInt… |
JSON has exactly six value types. Everything else must be converted to one of them before it can be stored as JSON.
➡️ JSON.stringify: Object to JSON Text
JSON.stringify(value, replacer, space) converts a JavaScript value into a JSON string. Use the third argument to indent the output for humans:
📄 stringify.js
const order = { id: 501, items: ["pen", "book"], paid: true, coupon: null };
const compact = JSON.stringify(order);
console.log(compact, typeof compact);
console.log(JSON.stringify(order, null, 2)); // 2-space indentation
console.log(JSON.stringify([1, "two", false]));
console.log(JSON.stringify("text"), JSON.stringify(42));
⌨️ Terminal
node stringify.js
🖥️ Output
{"id":501,"items":["pen","book"],"paid":true,"coupon":null} string
{
"id": 501,
"items": [
"pen",
"book"
],
"paid": true,
"coupon": null
}
[1,"two",false]
"text" 42
What stringify changes or drops
📄 stringify-rules.js
const data = {
name: "Asha",
nickname: undefined, // dropped
greet() { return "hi"; }, // dropped
joined: new Date(Date.UTC(2026, 10, 23)), // becomes an ISO string
score: NaN, // becomes null
limit: Infinity, // becomes null
tags: new Set(["a", "b"]), // becomes {}
list: [undefined, () => 1], // inside arrays: become null
};
console.log(JSON.stringify(data));
try {
JSON.stringify({ id: 10n });
} catch (e) {
console.log(e.constructor.name + ":", e.message);
}
⌨️ Terminal
node stringify-rules.js
🖥️ Output
{"name":"Asha","joined":"2026-11-23T00:00:00.000Z","score":null,"limit":null,"tags":{},"list":[null,null]}
TypeError: Do not know how to serialize a BigInt
⚠️ Watch out: These silent conversions cause real test bugs: a field set to undefined disappears from the request body, a Set is sent as {}, and a date becomes a string that must be parsed again on the other side. Convert values deliberately before sending them ([...set], date.toISOString(), String(bigint)).
🎛️ Replacer and toJSON: Control the Output
The second argument of stringify can be an array of keys to keep, or a replacer function called for every key and value. Return undefined to drop a property.
📄 replacer.js
const user = { id: 7, name: "Asha", password: "Secret@1", token: "abc", tags: new Set(["qa"]) };
console.log(JSON.stringify(user, ["id", "name"])); // allow-list
const safe = JSON.stringify(user, (key, value) => {
if (["password", "token"].includes(key)) return "***"; // mask secrets
if (value instanceof Set) return [...value]; // convert Sets
return value;
});
console.log(safe);
⌨️ Terminal
node replacer.js
🖥️ Output
{"id":7,"name":"Asha"}
{"id":7,"name":"Asha","password":"***","token":"***","tags":["qa"]}
An object can also define a toJSON() method; stringify uses its return value instead of the object. This is how Date turns itself into an ISO string.
📄 tojson.js
class Money {
constructor(amount, currency) { this.amount = amount; this.currency = currency; }
toJSON() { return `${this.amount.toFixed(2)} ${this.currency}`; }
}
console.log(JSON.stringify({ total: new Money(1299.5, "INR") }));
⌨️ Terminal
node tojson.js
🖥️ Output
{"total":"1299.50 INR"}
⬅️ JSON.parse: JSON Text to Object
JSON.parse(text, reviver) turns a JSON string into JavaScript values. This is what await response.json() does for you in Playwright and fetch.
📄 parse.js
const text = '{"id":501,"items":["pen","book"],"paid":true,"placedAt":"2026-11-23T10:30:00.000Z"}';
const order = JSON.parse(text);
console.log(order.items[1], order.paid, typeof order);
console.log(typeof order.placedAt); // dates stay strings
const withDates = JSON.parse(text, (key, value) =>
typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value) ? new Date(value) : value
);
console.log(withDates.placedAt instanceof Date, withDates.placedAt.getUTCHours());
⌨️ Terminal
node parse.js
🖥️ Output
book true object
string
true 10
The reviver function sees every key and value after parsing and can replace them, here turning ISO date strings back into Date objects.
Parse errors
Invalid JSON throws a SyntaxError. Common causes are single quotes, trailing commas, unquoted keys, and trying to parse something that is not JSON at all, such as an HTML error page:
📄 parse-errors.js
const samples = [
"{'id': 1}",
'{"id": 1,}',
"{id: 1}",
"<!DOCTYPE html><html>502 Bad Gateway</html>",
"",
];
for (const s of samples) {
try {
JSON.parse(s);
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
}
⌨️ Terminal
node parse-errors.js
🖥️ Output
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
SyntaxError: Expected double-quoted property name in JSON at position 9 (line 1 column 10)
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
SyntaxError: Unexpected end of JSON input
💡 Tip: When an API test fails with “Unexpected token <“, the server returned HTML (an error page or a login redirect) instead of JSON. Log the status code and the raw text before parsing; in Playwright, check response.status() and await response.text().
🔁 Circular References
An object that refers to itself (directly or through other objects) cannot be turned into JSON, because the output would be infinite:
📄 circular.js
const parent = { name: "suite" };
const child = { name: "test", parent };
parent.children = [child]; // parent -> child -> parent ...
try {
JSON.stringify(parent);
} catch (e) {
console.log(e.message.split("\n")[0]);
}
const seen = new WeakSet();
console.log(JSON.stringify(parent, (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
}
return value;
}));
⌨️ Terminal
node circular.js
🖥️ Output
Converting circular structure to JSON
{"name":"suite","children":[{"name":"test","parent":"[Circular]"}]}
Logging libraries and test reporters use a replacer like this one so that a circular object can still be printed.
📁 Reading and Writing JSON Files in Node.js
Test data and configuration often live in .json files. In Node.js, read the file as text with the fs module and parse it; write by stringifying with indentation:
📄 json-files.js
const fs = require("node:fs");
const users = [
{ username: "standard_user", password: "pass1", expected: "success" },
{ username: "locked_user", password: "pass2", expected: "locked" },
];
fs.writeFileSync("users.json", JSON.stringify(users, null, 2) + "\n");
console.log("written:", fs.readFileSync("users.json", "utf8").split("\n").length - 1, "lines");
const loaded = JSON.parse(fs.readFileSync("users.json", "utf8"));
for (const u of loaded) {
console.log(`${u.username.padEnd(14)} -> expect ${u.expected}`);
}
⌨️ Terminal
node json-files.js
🖥️ Output
written: 12 lines
standard_user -> expect success
locked_user -> expect locked
- Always pass
"utf8"so you get a string instead of a Buffer. - In CommonJS you can also
require("./users.json"); in ES modules useimport users from "./users.json" with { type: "json" }(import attributes). Both cache the file, so usefswhen the file can change during a run. - The Module 11 lesson on the file system covers async file reading and paths in depth.
🧬 Deep Copy: JSON Round-Trip vs structuredClone
JSON.parse(JSON.stringify(obj)) was the classic way to deep-copy an object. It works only for plain JSON-safe data. structuredClone(obj) (available everywhere since 2022) is the modern, safer choice:
📄 deep-copy.js
const original = {
name: "Asha",
joined: new Date(Date.UTC(2026, 0, 15)),
tags: new Set(["qa"]),
meta: { score: NaN, note: undefined },
};
const viaJson = JSON.parse(JSON.stringify(original));
const viaClone = structuredClone(original);
console.log("JSON :", viaJson);
console.log("clone :", viaClone);
console.log(viaClone.joined instanceof Date, viaClone.tags instanceof Set, viaClone.meta !== original.meta);
⌨️ Terminal
node deep-copy.js
🖥️ Output
JSON : {
name: 'Asha',
joined: '2026-01-15T00:00:00.000Z',
tags: {},
meta: { score: null }
}
clone : {
name: 'Asha',
joined: 2026-01-15T00:00:00.000Z,
tags: Set(1) { 'qa' },
meta: { score: NaN, note: undefined }
}
true true true
| JSON round-trip | structuredClone | |
|---|---|---|
| Dates | Become strings | Stay Date objects |
| Map / Set | Become {} | Copied correctly |
| undefined, NaN, Infinity | Lost or become null | Kept |
| Circular references | Throw | Copied correctly |
| Functions, class methods | Dropped | Throw DataCloneError (functions) / prototype lost |
🧪 Tester Scenario: Compare an API Response with a Fixture
A typical API test loads an expected response from a JSON fixture, ignores fields that change on every call (IDs, timestamps), and compares the rest:
📄 fixture.js
const { isDeepStrictEqual } = require("node:util");
const fixtureText = `{
"name": "Asha",
"role": "tester",
"permissions": ["read", "write"],
"id": 0,
"createdAt": ""
}`;
const responseText = '{"id":9123,"name":"Asha","role":"tester","permissions":["read","write"],"createdAt":"2026-11-23T10:31:07Z"}';
const IGNORE = ["id", "createdAt"];
const strip = (obj) => JSON.parse(JSON.stringify(obj, (k, v) => (IGNORE.includes(k) ? undefined : v)));
const expected = strip(JSON.parse(fixtureText));
const actual = strip(JSON.parse(responseText));
console.log("matches fixture:", isDeepStrictEqual(actual, expected));
console.log("dynamic fields present:", Number.isInteger(JSON.parse(responseText).id), !Number.isNaN(Date.parse(JSON.parse(responseText).createdAt)));
⌨️ Terminal
node fixture.js
🖥️ Output
matches fixture: true
dynamic fields present: true true
- The replacer returns
undefinedfor ignored keys, which removes them before comparing. - Dynamic fields are not ignored completely: the test still checks their type and format.
- In Playwright,
expect(body).toMatchObject(expected)andexpect.any(Number)express the same idea.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Convert { name: "Lamp", price: 899, tags: ["home"] } to a JSON string with 4-space indentation and print it.
Show answer
📄 practice1.js
const product = { name: "Lamp", price: 899, tags: ["home"] };
console.log(JSON.stringify(product, null, 4));🖥️ Output
{
"name": "Lamp",
"price": 899,
"tags": [
"home"
]
}Q2. Parse '{"total": 1299.5, "items": 3}' and print the average price per item rounded to 2 decimals.
Show answer
📄 practice2.js
const data = JSON.parse('{"total": 1299.5, "items": 3}');
console.log((data.total / data.items).toFixed(2));🖥️ Output
433.17Q3. Write safeParse(text) that returns { ok: true, data } on success and { ok: false, error } on a parse error.
Show answer
📄 practice3.js
function safeParse(text) {
try {
return { ok: true, data: JSON.parse(text) };
} catch (e) {
return { ok: false, error: e.message };
}
}
console.log(safeParse('{"a":1}'));
console.log(safeParse("{a:1}"));🖥️ Output
{ ok: true, data: { a: 1 } }
{
ok: false,
error: "Expected property name or '}' in JSON at position 1 (line 1 column 2)"
}Q4. Stringify a user object but mask the email so only the first letter and domain show, for example a***@sqatools.in.
Show answer
📄 practice4.js
const user = { name: "Asha", email: "asha@sqatools.in" };
const json = JSON.stringify(user, (key, value) =>
key === "email" ? value[0] + "***" + value.slice(value.indexOf("@")) : value
);
console.log(json);🖥️ Output
{"name":"Asha","email":"a***@sqatools.in"}Q5. Predict the output of JSON.stringify({ a: undefined, b: null, c: [undefined], d: NaN }), then run it.
Show answer
📄 practice5.js
console.log(JSON.stringify({ a: undefined, b: null, c: [undefined], d: NaN }));🖥️ Output
{"b":null,"c":[null],"d":null}a is dropped, null is kept, undefined inside an array becomes null, and NaN becomes null.
Q6. Write a JSON file config.json with { "env": "qa", "retries": 2 }, read it back, increase retries by 1 and save it again. Print the final file content.
Show answer
📄 practice6.js
const fs = require("node:fs");
fs.writeFileSync("config.json", JSON.stringify({ env: "qa", retries: 2 }, null, 2));
const config = JSON.parse(fs.readFileSync("config.json", "utf8"));
config.retries += 1;
fs.writeFileSync("config.json", JSON.stringify(config, null, 2));
console.log(fs.readFileSync("config.json", "utf8"));🖥️ Output
{
"env": "qa",
"retries": 3
}🧠 MCQ Quiz: JSON and Deep Copy
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which is valid JSON?Answer: {“name”: “Asha”}. JSON requires double-quoted keys and strings and allows no trailing commas.
- What does
JSON.stringify({ a: 1 })return?Answer: The string ‘{“a”:1}’. stringify always returns a string (or undefined for unsupported top-level values). - What happens to a property whose value is undefined in JSON.stringify?Answer: It is left out. Inside arrays, undefined becomes null instead.
- What does a Date become after JSON.stringify and JSON.parse?Answer: An ISO date string. Use a reviver or new Date() to turn it back into a Date.
- What error does
JSON.parse("{a:1}")throw?Answer: SyntaxError. Keys must be in double quotes. - What does the third argument of JSON.stringify control?Answer: Indentation. The second argument is the replacer.
- Why does
JSON.stringify(obj)throw “Converting circular structure to JSON”?Answer: The object refers back to itself. Use a replacer that tracks seen objects, or remove the cycle. - Which method creates a deep copy that keeps Dates, Maps and Sets?Answer: structuredClone. The JSON round-trip loses those types.
- An API test fails with “Unexpected token ‘<‘” while parsing JSON. What is the likely cause?Answer: The server returned HTML instead of JSON. Check the status code and raw text.
- What does
JSON.stringify(10n)do?Answer: Throws a TypeError. Convert BigInt values to strings first.
💼 Interview Questions and Answers
Q1. What is the difference between JSON and a JavaScript object?
JSON is a language-independent text format; a JavaScript object is an in-memory value. JSON requires double-quoted keys and strings, has no comments or trailing commas, and supports only strings, numbers, booleans, null, objects and arrays. JSON.stringify serialises an object to JSON text and JSON.parse deserialises JSON text into objects.
Q2. What gets lost when you deep-copy with JSON.parse(JSON.stringify(obj))?
undefined properties and functions are dropped; NaN and Infinity become null; Date objects become strings; Map, Set and class instances become plain objects; BigInt throws; circular references throw. structuredClone handles most of these correctly.
Q3. How would you hide sensitive fields when logging a request body?
📄 redact.js
const SENSITIVE = new Set(["password", "token", "authorization", "cardNumber"]);
const redact = (obj) => JSON.stringify(obj, (k, v) => (SENSITIVE.has(k) ? "[REDACTED]" : v), 2);
console.log(redact({ user: "asha", password: "x", headers: { authorization: "Bearer abc" } }));
⌨️ Terminal
node redact.js
🖥️ Output
{
"user": "asha",
"password": "[REDACTED]",
"headers": {
"authorization": "[REDACTED]"
}
}
A replacer function runs for every key at every depth, so nested secrets are redacted too.
Q4. How do you compare an API response against expected JSON when some fields are dynamic?
Remove or normalise the dynamic fields (IDs, timestamps, request IDs) before comparing, for example with a replacer or by destructuring them out, and assert their format separately (integer, ISO date, UUID). Compare the rest with deep equality (toEqual, toMatchObject, isDeepStrictEqual). For larger contracts, validate against a JSON Schema with a library such as Ajv.
❓ Frequently Asked Questions
🤔 How do I pretty-print JSON in JavaScript?
Use JSON.stringify(obj, null, 2). The third argument is the number of spaces (or a string such as "\t") used for indentation.
🤔 How do I read a JSON file in Node.js?
Use JSON.parse(fs.readFileSync("file.json", "utf8")), or the async fs.promises.readFile. In ES modules you can also use an import with { type: "json" }.
🤔 Why are my dates strings after JSON.parse?
JSON has no date type, so dates are stored as strings. Convert them with new Date(value) or a reviver function.
🤔 Can JSON have comments?
No. If you need comments in configuration, use a format that allows them (JSONC, YAML, or a JavaScript/TypeScript config file such as playwright.config.ts).
🏁 Summary
- JSON is text with strict rules: double quotes, no trailing commas, no comments, six value types.
JSON.stringify(value, replacer, space)creates JSON; it drops undefined and functions and converts dates to strings.JSON.parse(text, reviver)reads JSON and throwsSyntaxErroron invalid input, such as HTML error pages.- Read and write JSON files with
fsplus parse/stringify; use replacers to redact secrets and handle circular data. - Use
structuredClonefor deep copies; the JSON round-trip loses dates, Maps, Sets and special values.
Next, continue with Lesson 36: Map, Set, WeakMap, WeakSet.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in