Deep Dive into JSON, Parsing & Serialization
Published by Brayan K
JSON (JavaScript Object Notation) is a lightweight, text-based data format for storing and exchanging structured data, which you turn into JavaScript values with JSON.parse() and back into text with JSON.stringify().
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
JSON syntax does not establish the application contract
A parser answers whether text follows JSON grammar. It does not know whether quantity should be an integer, whether a field is required or whether a user is allowed to change a price. Validate the parsed value before passing it into application logic.
function readQuantity(text) {
// Parsing can succeed even when the application value has the wrong type.
const value = JSON.parse(text);
if (value === null || typeof value !== "object" || Array.isArray(value) ||
!Number.isSafeInteger(value.quantity) || value.quantity < 1)
throw new TypeError("quantity must be a positive safe integer");
return value.quantity;
}
console.log(readQuantity('{"quantity":2}'));
try { readQuantity('{"quantity":"2"}'); }
catch (error) { console.log(error.name, error.message); }
// ✅ Expected output:
// 2
// TypeError quantity must be a positive safe integerA valid JSON document can also be null, a boolean, a number, a string or an array. Checking only typeof value === "object" accepts null and arrays. JSON uses double-quoted keys and strings; comments, trailing commas, undefined and single-quoted strings are outside its grammar.
for (const text of ["null", "true", "7", '"hello"', "[]", "{}"]) {
const value = JSON.parse(text);
console.log(value === null ? "null" : Array.isArray(value) ? "array" : typeof value);
}
// ✅ Expected output:
// null
// boolean
// number
// string
// array
// objectfor (const text of ['{"a":1,}', "{'a':1}", "undefined"]) {
try { JSON.parse(text); }
catch (error) { console.log(error.name); }
}
// ✅ Expected output:
// SyntaxError
// SyntaxError
// SyntaxErrorParser error wording can differ by engine, so this panel checks the error category instead of promising a particular diagnostic sentence. Do not use eval or a Function constructor to accept JavaScript object syntax as “JSON.” That changes data parsing into code execution.
Stringification is a conversion, not a lossless clone
console.log(JSON.stringify({ a: undefined, b: () => 1, c: Symbol("x"), d: null }));
console.log(JSON.stringify([undefined, () => 1, Symbol("x"), null]));
console.log(JSON.stringify(undefined) === undefined);
// ✅ Expected output:
// {"d":null}
// [null,null,null,null]
// trueA missing object property, an explicit null and an array position are different states. JSON cannot represent undefined or functions. At the top level, stringify can return undefined rather than a string. Check that boundary before handing the result to storage or a response body.
console.log(JSON.stringify([NaN, Infinity, -Infinity, -0]));
const decoded = JSON.parse(JSON.stringify(-0));
console.log(Object.is(decoded, -0));
const large = JSON.parse('{"id":9007199254740993}');
console.log(Number.isSafeInteger(large.id), String(large.id));
// ✅ Expected output:
// [null,null,null,0]
// false
// false 9007199254740992Large integer identifiers should use a string contract when they must survive exactly. By the time an ordinary reviver receives a number, precision may already be lost. The newer reviver context can expose source text in supporting engines, but this lesson’s portable contract does not depend on that API.
JSON.stringify({ count: 2n });
// ✅ Expected error:
// TypeError: Do not know how to serialize a BigIntconst value = {
date: new Date("2024-01-01T00:00:00Z"),
map: new Map([["a", 1]]),
set: new Set(["a"])
};
const decoded = JSON.parse(JSON.stringify(value));
console.log(typeof decoded.date, decoded.date instanceof Date);
console.log(JSON.stringify(decoded.map), JSON.stringify(decoded.set));
// ✅ Expected output:
// string false
// {} {}A Date becomes text through its toJSON method; Map and Set do not expose their entries as enumerable JSON properties by default. Use an explicit schema for these values. Deep Copy vs Shallow Copy & Data Structures owns graph copying and structuredClone; JSON round-tripping is not a general replacement.
const shared = { value: 1 };
const copy = JSON.parse(JSON.stringify({ first: shared, second: shared }));
console.log(copy.first === copy.second);
const cycle = {}; cycle.self = cycle;
try { JSON.stringify(cycle); }
catch (error) { console.log(error.name); }
// ✅ Expected output:
// false
// TypeErrorReplacers and revivers have traversal rules
const value = { amount: 7, toJSON() { return { cents: this.amount * 100 }; } };
const seen = [];
const text = JSON.stringify(value, (key, item) => {
seen.push(key === "" ? "root" : key);
return item;
});
console.log(text, seen.join(","));
// ✅ Expected output:
// {"cents":700} root,centsA replacer is not automatically a privacy boundary. An object’s toJSON method or getter can run during serialization. Construct a plain selected data-transfer object before serializing trusted application state; do not hand arbitrary objects with behavior to a serializer and assume it is inert.
const seen = [];
const value = JSON.parse('{"items":[1,2],"keep":true}', (key, item) => {
seen.push(key === "" ? "root" : key);
return key === "0" ? undefined : item;
});
console.log(seen.join(","));
console.log(value.items.length, Object.hasOwn(value.items, 0));
console.log(JSON.stringify(value));
// ✅ Expected output:
// 0,1,items,keep,root
// 2 false
// {"items":[null,2],"keep":true}Children are revived before their containing object, and the root is visited with an empty key. Removing an array element leaves a hole; serializing that array later produces null in the position. A reviver that accidentally returns undefined for the root removes the whole result.
const value = JSON.parse('{"n":1}', (key, item) => {
if (key === "n") return item * 2;
});
console.log(value === undefined);
// ✅ Expected output:
// trueA generic “any object with a type property is a Date” reviver can misinterpret ordinary user data. Prefer a versioned schema with a precisely owned tagged shape, then validate its fields. A serialization convention must state collisions, unsupported values and migration behavior.
Duplicate keys and prototype-sensitive merging need explicit policy
const value = JSON.parse('{"role":"reader","role":"writer"}');
console.log(value.role, Object.keys(value).length);
// ✅ Expected output:
// writer 1After parsing, an ordinary object no longer records that a duplicate appeared in the text. If rejecting duplicate keys is part of your protocol, use a parser that detects them while reading; a later schema validator alone cannot reconstruct that information.
const parsed = JSON.parse('{"__proto__":{"marker":"changed"}}');
console.log(Object.hasOwn(parsed, "__proto__"), Object.getPrototypeOf(parsed) === Object.prototype);
const target = {};
Object.assign(target, parsed);
console.log(Object.getPrototypeOf(target).marker);
console.log(Object.hasOwn(Object.prototype, "marker"));
// ✅ Expected output:
// true true
// changed
// falseThis changes only the demonstration target’s prototype; it does not mutate Object.prototype. Parsing and unsafe merging are separate operations. Select known fields or use an appropriate dictionary representation instead of recursively merging untrusted keys into application objects. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns the broader trust boundary.
const a = { first: 1, second: 2 };
const b = { second: 2, first: 1 };
console.log(JSON.stringify(a) === JSON.stringify(b));
console.log(JSON.stringify({ 10: "ten", 2: "two", name: "value" }));
// ✅ Expected output:
// false
// {"2":"two","10":"ten","name":"value"}JSON text can represent equivalent data with different key orders or whitespace. Do not create signatures or semantic cache keys by assuming every equivalent object stringifies identically. A canonicalization protocol needs its own rules; pretty printing is presentation, not canonicalization.
Guided exercise: select a public JSON record
Use literal hints to include only the intended fields. The resulting object is a transfer shape, not a copy of every property in the original account.
const account = { id: "u-1", name: "Mia", token: "private" };
const selected = { id: account.___, name: account.name }; // 👉 replace ___ with id
const text = JSON.___(selected); // 👉 replace ___ with stringify
const decoded = JSON.___(text); // 👉 replace ___ with parse
console.log(text);
console.log(Object.hasOwn(decoded, "token"));
// ✅ Expected output:
// {"id":"u-1","name":"Mia"}
// falseIndependent brief: decode a versioned cart document
Implement decodeCartJSON(text). Accept a string of at most 20,000 UTF-16 code units and parse it as JSON. Require exactly version, currency and items at the root, with version 1, currency GBP and 1 through 50 items. Each item has exactly sku, quantity and pricePence. Trim the SKU and require 1 through 32 code units, reject duplicate trimmed SKUs, require an integer quantity from 1 through 99 and integer pricePence from zero through 1,000,000. Reject unknown fields and coercions.
Return a new normalized record with those fields and totalPence. Bounds keep the computed total within the safe integer range. Preserve syntax errors from JSON.parse and use explicit schema errors for invalid shapes. This is a local data-format exercise: a server must still obtain trusted prices and enforce authorization; client-supplied prices are not an authority.
function decodeCartJSON(text) {
if (typeof text !== "string" || text.length > 20_000)
throw new TypeError("input must be JSON text up to 20000 code units");
const value = JSON.parse(text);
const exactFields = (object, fields) =>
object !== null && typeof object === "object" && !Array.isArray(object) &&
Object.keys(object).length === fields.length &&
fields.every(key => Object.hasOwn(object, key));
if (!exactFields(value, ["version", "currency", "items"]) ||
value.version !== 1 || value.currency !== "GBP" ||
!Array.isArray(value.items) || value.items.length < 1 || value.items.length > 50)
throw new TypeError("cart must use the version 1 GBP schema");
const seen = new Set(), items = [];
let totalPence = 0;
for (const row of value.items) {
if (!exactFields(row, ["sku", "quantity", "pricePence"]) ||
typeof row.sku !== "string" || row.sku.trim().length < 1 ||
row.sku.trim().length > 32 ||
!Number.isSafeInteger(row.quantity) || row.quantity < 1 || row.quantity > 99 ||
!Number.isSafeInteger(row.pricePence) || row.pricePence < 0 || row.pricePence > 1_000_000)
throw new TypeError("item does not match the cart schema");
const sku = row.sku.trim();
if (seen.has(sku)) throw new RangeError("duplicate sku");
seen.add(sku);
items.push({ sku, quantity: row.quantity, pricePence: row.pricePence });
totalPence += row.quantity * row.pricePence;
}
return { version: 1, currency: "GBP", items, totalPence };
}
const text = '{"version":1,"currency":"GBP","items":[{"sku":" A ","quantity":2,"pricePence":125},{"sku":"B","quantity":1,"pricePence":0}]}';
console.log(JSON.stringify(decodeCartJSON(text)));
const base = JSON.parse(text);
for (const change of [
cart => { cart.version = 2; },
cart => { cart.items[0].quantity = "2"; },
cart => { cart.items[1].sku = "A"; },
cart => { cart.secret = "omit"; }
]) {
const cart = JSON.parse(text); change(cart);
try { decodeCartJSON(JSON.stringify(cart)); }
catch (error) { console.log(error.name, error.message); }
}
console.log(base.items[0].sku === " A ");
// ✅ Expected output:
// {"version":1,"currency":"GBP","items":[{"sku":"A","quantity":2,"pricePence":125},{"sku":"B","quantity":1,"pricePence":0}],"totalPence":250}
// TypeError cart must use the version 1 GBP schema
// TypeError item does not match the cart schema
// RangeError duplicate sku
// TypeError cart must use the version 1 GBP schema
// trueReference notes
The JSON.parse reference documents reviver traversal and number precision. The JSON.stringify reference documents omission, toJSON and serialization failures.
Practice quiz
What does this complete program print? console.log(typeof JSON.parse("7"),JSON.parse("null")===null);
- number true
- string false
- object true
- number false
Answer: number true. JSON documents can contain primitive values.
What does this complete program print? console.log(JSON.stringify({x:undefined,y:null}));
- {"x":null,"y":null}
- {"y":null}
- {}
- undefined
Answer: {"y":null}. Undefined object properties are omitted while null remains.
What does this complete program print? console.log(JSON.stringify([undefined,NaN]));
- []
- [undefined,NaN]
- [null,null]
- undefined
Answer: [null,null]. Both array positions serialize as null.
What does this complete program print? const x=JSON.parse('{"id":9007199254740993}');console.log(Number.isSafeInteger(x.id));
- true
- undefined
- SyntaxError
- false
Answer: false. The numeric result is outside the safe integer range.
What does this complete program print? const x=JSON.parse('{"a":1}',()=>undefined);console.log(x===undefined);
- true
- false
- null
- SyntaxError
Answer: true. Removing the root removes the result.
What does this complete program print? const x=JSON.parse('{"n":1,"n":2}');console.log(x.n);
- 1
- 2
- undefined
- SyntaxError
Answer: 2. Ordinary JSON.parse retains the last duplicate value.
What does this complete program print? const shared={x:1};const out=JSON.parse(JSON.stringify([shared,shared]));console.log(out[0]===out[1]);
- true
- undefined
- false
- TypeError
Answer: false. Serialization does not preserve shared object identity.
What does this complete program print? const x=JSON.parse('[1,2]',(key,value)=>key==="0"?undefined:value);console.log(x.length,Object.hasOwn(x,0));
- 1 false
- 2 true
- 1 true
- 2 false
Answer: 2 false. A reviver deletion leaves an array hole.
Continue this course
- Previous: Writing Maintainable & Scalable Code Architecture
- Next: Client-Side Security Essentials (XSS, CSRF, Sanitisation) — Prevent the most common web security vulnerabilities in JS apps
- Quick reference: JavaScript cheat sheet