By the end of this lesson
Validate a list of task records instead of treating every parsed value as usable.
Before you start
- Node.js 24 with a terminal and plain-text editor; the browser-only lesson is labelled separately.
- Complete lesson 19 or be comfortable with its examples.
Three words to know
- JSON
- A text format for data, not JavaScript source code.
- Parsing
- Converting text that follows a grammar into values.
- Contract
- The requirements a program imposes after parsing.
1. Parse without executing
JSON.parse reads a JSON document; it does not run a script. Never use eval as a JSON parser. Objects and arrays become JavaScript objects and arrays, but a successful parse says nothing about the required fields or their meanings.
const records = JSON.parse('[{"title":"Read","status":"open"}]');
console.log(Array.isArray(records));
console.log(records[0].status);
What you should see · example output
true open
2. Validate the decoded shape
The short check below requires a list of records with supported statuses. It deliberately allows extra fields and does not bound file size; the project tightens those rules. Check the type before accessing a field so null and arrays do not slip through as ordinary records.
function validateRecords(records) {
if (!Array.isArray(records)) throw new Error("Expected an array");
for (const record of records) {
if (record === null || typeof record !== "object" || Array.isArray(record)) {
throw new Error("Expected objects");
}
if (record.status !== "open" && record.status !== "closed") {
throw new Error("Unsupported status");
}
}
return records.length;
}
console.log(validateRecords([{ status: "open" }]));
What you should see · example output
1
3. Know the parser’s boundaries
JSON.parse uses the last value when an object key appears more than once. A numeric literal too large for Number can become Infinity, even though the literal was valid JSON text. A format that requires duplicate-key rejection or exact large integers needs an appropriate parser or pre-agreed encoding, not an assumption that ordinary JSON.parse detects everything.
const result = { records: 2, open: 1 };
console.log(JSON.stringify(result));
What you should see · example output
{"records":2,"open":1}
YOUR TURN
A small check before you continue
Is {"status":"open"} valid JSON? Does it meet the list requirement? What does a duplicate status key do with ordinary JSON.parse?
Show a suggested answer
It is valid JSON but is not the required outer array. Ordinary JSON.parse retains the last duplicate property value; do not claim it rejected duplicates.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
