Exchange and Validate JSON
Exchange and Validate JSON
JSON is a text format, not a live JavaScript object. JSON.parse produces values; the school must then verify the fields and allowed ranges before using them. Successful parsing alone does not mean a valid student.
Before this topic, review Copy Objects Without Sharing Every Field if its terms are unfamiliar.
What you’ll learn
- Explain exchange and validate json through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The text parses successfully, but its numeric mark fails the school range rule.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
const student = JSON.parse('{"marks":72}');
console.log(Number.isFinite(student.marks) && student.marks >= 0 && student.marks <= 100);
Expected output
trueRun in JavaScript compiler →Recognize the important boundary
JSON does not preserve functions, undefined object properties or a Date instance as a Date. Parsing invalid text throws; validate external data's structure.
Try a small variation
JavaScript · original source for practice
const student = JSON.parse('{"marks":72}');
console.log(Number.isFinite(student.marks) && student.marks >= 0 && student.marks <= 100);
Your task: Replace "marks":72 with "marks":101. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The text parses successfully, but its numeric mark fails the school range rule.
JavaScript · complete worked variation
const student = JSON.parse('{"marks":101}');
console.log(Number.isFinite(student.marks) && student.marks >= 0 && student.marks <= 100);
Expected output
falseRun in JavaScript compiler →Predict the original program
JavaScript · original program for this question
const student = JSON.parse('{"marks":72}');
console.log(Number.isFinite(student.marks) && student.marks >= 0 && student.marks <= 100);
Check the important distinction
Keep the useful idea
JSON is a text format, not a live JavaScript object. JSON.parse produces values; the school must then verify the fields and allowed ranges before using them. Successful parsing alone does not mean a valid student.
Check your variation against this explanation: The text parses successfully, but its numeric mark fails the school range rule.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.